package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppElevatorAuthDTO;
import com.itlong.cloud.POJO.DTO.app.AppFaceRecognitionDeviceAuthDTO;
import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyDeviceCloudControllerGetDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.app.*;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.POJO.VO.smartcard.SmartCardIncrementUpdateGetVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.app.service.IAppDeviceService;
import com.itlong.cloud.commons.thread.queue.process.queue.SendIotPushMessageQueue;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.property.dao.IPadFaceSyncDataServiceDao;
import com.itlong.cloud.property.dao.IPropertyPadDao;
import com.itlong.cloud.property.service.IDeviceCloudControllerService;
import com.itlong.cloud.property.service.IPadFaceSyncDataService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.file.ImgageUtil;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.picture.VerifyCodeUtils;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      平板人脸增量同步数据服务接口实现类
 * </desc>
 *
 * @createDate 2019/01/17
 */
@Service
public class PadFaceSyncDataServiceImpl implements IPadFaceSyncDataService {

    private static final Logger LOG = LoggerFactory.getLogger(PadFaceSyncDataServiceImpl.class);

    @Autowired
    private IPadFaceSyncDataServiceDao iPadFaceSyncDataServiceDao;

    @Autowired
    private IAppDeviceService iAppDeviceService;

    @Autowired
    SendIotPushMessageQueue sendIotPushMessageQueue;

    @Autowired
    MessageSender messageSender;

    @Autowired
    RedisService redisService;

    @Autowired
    IPropertyPadDao iPropertyPadDao;

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    @Autowired
    IDeviceCloudControllerService iDeviceCloudControllerService;

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    private static ExecutorService importAddressFixedThreadPool = Executors.newFixedThreadPool(20); // 同步数据线程池

    /**
     * <desc>
     *      住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据，异步执行
     * </desc>
     *
     * @param padFaceSyncDataDTO 平板人脸增量同步数据DTO
     * @return 0失败，1成功
     * @author wangzhi
     * @createDate 2019/01/17
     */
    @Override
    public Integer userOrFloorSync(PadFaceSyncDataDTO padFaceSyncDataDTO) throws Exception {
        importAddressFixedThreadPool.execute(() -> {
            try {
                int i = userOrFloorSyncExecute(padFaceSyncDataDTO);
                if (i == 1) {
                    //LOG.info("【住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据执行成功】" + padFaceSyncDataDTO);
                } else {
                    LOG.info("【住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据执行失败，但无异常】" + padFaceSyncDataDTO);
                }
            } catch (Exception e) {
                LOG.error("【住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据执行失败】" + padFaceSyncDataDTO, e);
            }
        });
        return 1;
    }

    /**
     * <desc>
     *      住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据，异步执行
     * </desc>
     *
     * @param padFaceSyncDataDTO 人脸增量同步数据DTO
     * @return 0失败，1成功
     * @author wangzhi
     * @createDate 2019/03/19
     */
    @Override
    public Integer userOrFloorSyncSmartCard(PadFaceSyncDataDTO padFaceSyncDataDTO) throws Exception {
        importAddressFixedThreadPool.execute(() -> {
            try {
                int i = userOrFloorSyncExecuteSmartCard(padFaceSyncDataDTO);
                if (i == 1) {
                    //LOG.info("【住户信息变更和楼层映射信息变更触发一卡通动态人脸识别同步数据执行成功】" + padFaceSyncDataDTO);
                } else {
                    LOG.info("【住户信息变更和楼层映射信息变更触发一卡通动态人脸识别同步数据执行失败，但无异常】" + padFaceSyncDataDTO);
                }
            } catch (Exception e) {
                LOG.error("【住户信息变更和楼层映射信息变更触发一卡通动态人脸识别同步数据执行失败】" + padFaceSyncDataDTO, e);
            }
        });
        return 1;
    }

    /**
     * <desc>
     *      住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据
     * </desc>
     *
     * @param padFaceSyncDataDTO 平板人脸增量同步数据DTO
     * @return 0失败，1成功
     * @author wangzhi
     * @createDate 2019/01/17
     */
    private Integer userOrFloorSyncExecute(PadFaceSyncDataDTO padFaceSyncDataDTO) throws Exception {
        // 人脸注册那边是异步，这边5秒后再开始
        Thread.sleep(5000);
        Date nowTime = new Date();
        List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
        List<PadPullCloudInfoPO> padPullCloudInfoPOAllList = new ArrayList<>();
        // 操作类型，"0"住户冻结、解冻
        if ("0".equals(padFaceSyncDataDTO.getOperateType()))
        {
            // 没有用户id时传房间id
            if (StringUtils.isBlank(padFaceSyncDataDTO.getAppUserIds())) {
                List<String> roomIdList = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getRoomId());
                String userIds = iPadFaceSyncDataServiceDao.getUserIdByRoomId(roomIdList);
                if (StringUtils.isBlank(userIds)) {
                    return 1;
                }
                padFaceSyncDataDTO.setAppUserIds(userIds);
            }
            List<String> appUserIds = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getAppUserIds());
            List<Map<String, Object>> SyncDataListMap = new ArrayList<>();
            // 先以userId为单位拿到需要更新的数据
            for (String appUserId : appUserIds){
                String facePicUrl = iPadFaceSyncDataServiceDao.getFacePicUrl(appUserId,padFaceSyncDataDTO.getProjectId());
                if (StringUtils.isBlank(facePicUrl)) {
                    continue;
                }
                String username = iPadFaceSyncDataServiceDao.getUsername(appUserId);
                List<String> roomIds = iPadFaceSyncDataServiceDao.getAppUserRoomId(appUserId,padFaceSyncDataDTO.getProjectId());
                List<String> buildIds = iPadFaceSyncDataServiceDao.getBuildIdsOfUser(appUserId,padFaceSyncDataDTO.getProjectId());
                List<String> deviceUniques = iPadFaceSyncDataServiceDao.getPadDeviceUniques(buildIds);
                //TODO 此处需要根据用户分组的门禁电梯权限 查出与其设备绑定的平板设备，并与以地址查出来平板设备进行去重
                if (deviceUniques == null || deviceUniques.isEmpty()) {
                    continue;
                }
                for (String deviceUnique : deviceUniques){
                    Map<String, Object> map = new HashMap<>();
                    map.put("deviceUnique", deviceUnique);
                    map.put("username", username == null ? "" : username);
                    map.put("userId", appUserId);
                    map.put("imageUrl", facePicUrl);
                    // 用户禁用启用状态 1正常 5禁用 4冻结 2欠费
                    if (StringUtils.isNotBlank(padFaceSyncDataDTO.getStatus())) {
                        map.put("status", padFaceSyncDataDTO.getStatus());
                    } else {
                        // 先判断用户项目冻结状态
                        map.put("status", "1".equals(iPadFaceSyncDataServiceDao.getUserProjectStatus(appUserId,padFaceSyncDataDTO.getProjectId())) ? "1" : "4");
                        // 用户未冻结，则判断用户禁用状态
                        if ("1".equals(map.get("status"))) {
                            map.put("status","1".equals(iPadFaceSyncDataServiceDao.getUserStatus(appUserId)) ? "1" : "5");
                        }
                    }
                    // 用户是否欠物业费用 0是 1否 2019/02/14 下午与有为沟通后，废弃此字段，合在上面status字段中
                    map.put("outstandingAccounts", "1");
                    Integer accountByRoomId = null;
                    if (roomIds != null && !roomIds.isEmpty()) {
                        accountByRoomId = iPadFaceSyncDataServiceDao.getOverdueCountByRoomId(roomIds, deviceUnique);
                    }
                    if (accountByRoomId != null && accountByRoomId > 0) {
                        map.put("outstandingAccounts", "0");
                        // 正常人员才会有欠费状态
                        if ("1".equals(map.get("status"))) {
                            map.put("status","2");
                        }
                    }
                    //组装vip标签
                    List<PadFaceUserInfoNewVO> userInfoByUserId =
                            iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(deviceUnique.substring(0, 8)), appUserId);
                    for (PadFaceUserInfoNewVO userInfoNewVO : userInfoByUserId) {
                        if (userInfoNewVO.getUserLabel()==null){
                            map.put("isVip","0");
                        }else {
                            map.put("isVip",(Arrays.asList(userInfoNewVO.getUserLabel().split(",")).contains("1")?1:0));
                        }
                    }

                    SyncDataListMap.add(map);
                }
            }
            // 再以deviceUnique为单位组装需要插入的同步数据
            if (SyncDataListMap.isEmpty()) {
                return 1;
            }
            Map<String,List<PadFaceSyncDataUserVO>> SyncDataMapList = new HashMap<>();
            for (Map map : SyncDataListMap){
                PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
                padFaceSyncDataUserVO.setUserName(map.get("username").toString());
                padFaceSyncDataUserVO.setUserId(map.get("userId").toString());
                padFaceSyncDataUserVO.setImageUrl(map.get("imageUrl").toString());
                padFaceSyncDataUserVO.setStatus(map.get("status").toString());
                padFaceSyncDataUserVO.setOutstandingAccounts(map.get("outstandingAccounts")==null?"":map.get("outstandingAccounts").toString());
                padFaceSyncDataUserVO.setHouseUserType("5");
                padFaceSyncDataUserVO.setStartTime("");
                padFaceSyncDataUserVO.setEndTime("");
                padFaceSyncDataUserVO.setIsVip(Integer.getInteger(map.get("isVip")==null?"0":map.get("isVip").toString()));
                String deviceUnique = map.get("deviceUnique").toString();
                if (SyncDataMapList.get(deviceUnique) == null) {
                    List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                    list.add(padFaceSyncDataUserVO);
                    SyncDataMapList.put(deviceUnique,list);
                } else {
                    SyncDataMapList.get(deviceUnique).add(padFaceSyncDataUserVO);
                }
            }
            if (SyncDataMapList.isEmpty()) {
                return 1;
            }
            // 组装插入表的数据
            SyncDataMapList.forEach((key, value) -> {
                for (PadFaceSyncDataUserVO vo : value) {
                    List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                    list.add(vo);
                    PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                    padPullCloudInfoPO.setDeviceUnique(key);
                    padPullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                    String syncData = JSON.toJSONString(list);
                    padPullCloudInfoPO.setSyncData(syncData);
                    padPullCloudInfoPO.setSyncType(2);
                    padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO.setDataType(1);
                    padPullCloudInfoPO.setSyncStatus(1);
                    padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO.setCreateTime(nowTime);
                    padPullCloudInfoPO.setUpdateTime(nowTime);
                    padPullCloudInfoPO.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                    padPullCloudInfoPO.setInstructionType(0);
                    padPullCloudInfoPOList.add(padPullCloudInfoPO);
                    iPadFaceSyncDataServiceDao.updatePadOrderByUser(list.get(0).getUserId(),key);//清除当前设备,当前用户之前的1号指令
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO);
                }
            });
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        } else if ("1".equals(padFaceSyncDataDTO.getOperateType()))
        { // 操作类型，"1"人脸注册
            String facePicUrl = iPadFaceSyncDataServiceDao.getFacePicUrl(padFaceSyncDataDTO.getAppUserIds(),padFaceSyncDataDTO.getProjectId());
            List<String> roomIds = iPadFaceSyncDataServiceDao.getAppUserRoomId(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId());
            String username = iPadFaceSyncDataServiceDao.getUsername(padFaceSyncDataDTO.getAppUserIds());
            List<String> buildIds = iPadFaceSyncDataServiceDao.getBuildIdsOfUser(padFaceSyncDataDTO.getAppUserIds(),padFaceSyncDataDTO.getProjectId());
            List<String> deviceUniques = new ArrayList<>();
            if (buildIds !=null && !buildIds.isEmpty()){
                deviceUniques = iPadFaceSyncDataServiceDao.getPadDeviceUniques(buildIds);
            }

            //查询用户的常用楼层和公共楼层
            List<PadFaceUserInfoNewVO> userInfo =
                    iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(padFaceSyncDataDTO.getAppUserIds()), padFaceSyncDataDTO.getProjectId());
            String commonFloor=null;
            String publicFloor=null;
            for (PadFaceUserInfoNewVO userInfoNewVO : userInfo) {
                commonFloor = userInfoNewVO.getCommonFloor();
                publicFloor = userInfoNewVO.getPublicFloor();
            }
            Map jsonCommonFloor=null;
            Map jsonPublicFloor=null;
            if (commonFloor!=null){
                jsonCommonFloor = JSON.parseObject(commonFloor, HashMap.class);
            }
            if (publicFloor!=null){
                jsonPublicFloor =  JSON.parseObject(publicFloor, HashMap.class);
            }


            List<Map<String,Object>> authsDoor = new ArrayList<>();
            if (true) {
                //平板绑定普通门禁有没地址信息
                //此处进行设备是否绑定普通门禁,并是否对此用户有权限进行判断
                //根据用户编号找到选中的角色编号,根据角色编号找到普通门禁,根据普通门禁找到绑定的平板
                List<String> doorList = iPadFaceSyncDataServiceDao.getDoorDeviceUniqueByUserId(padFaceSyncDataDTO.getAppUserIds(),padFaceSyncDataDTO.getProjectId());
                if (doorList != null && doorList.size() > 0) {
                    List<String> deviceUniquesByTemAuth = iPadFaceSyncDataServiceDao.getPadDeviceUniquesByDoor(doorList);
                    if (true) {
                        if(deviceUniques!=null && deviceUniques.size()>0){
                            deviceUniques.addAll(deviceUniquesByTemAuth);
                        }else{
                            deviceUniques = deviceUniquesByTemAuth;
                        }
                        Map<String, Object> authDoor = new HashMap<>();
                        List<Map<String, Object>> sysAuthDoor = new ArrayList<>();
                        authDoor.put("userId", padFaceSyncDataDTO.getAppUserIds());
                        authDoor.put("houseUserType", "5");
                        authDoor.put("startTime", "");
                        authDoor.put("endTime", "");
                        authDoor.put("deviceType", 3);//普通门禁用3
                        for (String door : doorList) {
                            Map<String, Object> sysAuth = new HashMap<>();
                            sysAuth.put("auth", "8");
                            sysAuth.put("deviceUnique", door);
                          if (commonFloor==null){
                              sysAuth.put("commonFloor","");
                          }else {
                              StringBuilder builder = new StringBuilder();


                              if (jsonCommonFloor.containsKey(door)){

                                  builder.append(jsonCommonFloor.get(door)).append(",");
                              }
                              sysAuth.put("commonFloor",("".equals(builder+""))?"":builder.toString().substring(0,builder.length()-1));
                          }
                          if (publicFloor==null){
                                sysAuth.put("publicFloor","");
                            }else {
                              StringBuilder builderp = new StringBuilder();

                              if (jsonPublicFloor.containsKey(door)){
                                  builderp.append(jsonPublicFloor.get(door)).append(",");
                              }
                              sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));

                          }

                            sysAuthDoor.add(sysAuth);
                        }
                        authDoor.put("sysAuths", sysAuthDoor);
                        authsDoor.add(authDoor);
                    } else {
                        return 1;
                    }
                } else {
                    return 1;
                }
            }
            // 同时要给到用户设备权限
            // 门禁
            List<AppDoorDevicesVO> doorDevices = iAppDeviceService.getDoorDevices(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId(), 1);
            if (doorDevices != null && !doorDevices.isEmpty()) {
                Map<String, Object> authDoor = new HashMap<>();
                List<Map<String,Object>> sysAuthDoor = new ArrayList<>();
                authDoor.put("userId",padFaceSyncDataDTO.getAppUserIds());
                authDoor.put("houseUserType","5");
                authDoor.put("startTime","");
                authDoor.put("endTime","");
                authDoor.put("deviceType",1);
                for (AppDoorDevicesVO door : doorDevices) {
                    Map<String,Object> sysAuth = new HashMap<>();
                    sysAuth.put("auth","8");
                    sysAuth.put("deviceUnique",door.getDeviceUnique());
                    if (commonFloor==null){
                        sysAuth.put("commonFloor","");
                    }else {
                        StringBuilder builder = new StringBuilder();


                        if (jsonCommonFloor.containsKey(door)){
                            System.out.println(jsonCommonFloor.get(door));
                            builder.append(jsonCommonFloor.get(door)).append(",");
                        }
                        sysAuth.put("commonFloor",("".equals(builder+""))?"":(builder.toString().substring(0,(builder.length()-1))));
                    }
                    if (publicFloor==null){
                        sysAuth.put("publicFloor","");
                    }else {
                        StringBuilder builderp = new StringBuilder();

                        if (jsonPublicFloor.containsKey(door)){
                            builderp.append(jsonPublicFloor.get(door)).append(",");
                        }
                        sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));
                    }
                    sysAuthDoor.add(sysAuth);
                }
                authDoor.put("sysAuths",sysAuthDoor);
                authsDoor.add(authDoor);
            }

            // 电梯
            List<AppFloorDevicesVO> floorDevices = iAppDeviceService.getFloorDevices(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId(), 1);
            List<Map<String,Object>> authsElevator = new ArrayList<>();
            if (floorDevices != null && !floorDevices.isEmpty()) {
                Map<String, Object> authElevator = new HashMap<>();
                List<Map<String,Object>> sysAuthElevator = new ArrayList<>();
                authElevator.put("userId",padFaceSyncDataDTO.getAppUserIds());
                authElevator.put("houseUserType","5");
                authElevator.put("startTime","");
                authElevator.put("endTime","");
                authElevator.put("deviceType",2);
                for (AppFloorDevicesVO floor : floorDevices) {
                    Map<String,Object> sysAuth = new HashMap<>();
                    sysAuth.put("auth",floor.getLiveFloor());
                    sysAuth.put("deviceUnique",floor.getDeviceUnique());
                    if (commonFloor==null){
                        sysAuth.put("commonFloor","");
                    }else {
                        StringBuilder builder = new StringBuilder();


                        if (jsonCommonFloor.containsKey(floor)){
                            builder.append(jsonCommonFloor.get(floor)).append(",");
                        }
                        sysAuth.put("commonFloor",("".equals(builder+""))?"":(builder.toString().substring(0,(builder.length()-1))));

                    }
                    if (publicFloor==null){
                        sysAuth.put("publicFloor","");
                    }else {
                        StringBuilder builderp = new StringBuilder();

                        if (jsonPublicFloor.containsKey(floor)){
                            builderp.append(jsonPublicFloor.get(floor)).append(",");
                        }
                        sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));

                    }
                    sysAuthElevator.add(sysAuth);
                }
                authElevator.put("sysAuths",sysAuthElevator);
                authsElevator.add(authElevator);
            }

            // 用户信息
            PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
            padFaceSyncDataUserVO.setUserName(username == null ? "" : username);
            padFaceSyncDataUserVO.setUserId(padFaceSyncDataDTO.getAppUserIds());
            padFaceSyncDataUserVO.setImageUrl(facePicUrl);
            // 先判断用户项目冻结状态
            String status = "1".equals(iPadFaceSyncDataServiceDao.getUserProjectStatus(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId())) ? "1" : "4";
            // 用户未冻结，则判断用户禁用状态
            if ("1".equals(status)) {
                status = "1".equals(iPadFaceSyncDataServiceDao.getUserStatus(padFaceSyncDataDTO.getAppUserIds())) ? "1" : "5";
            }
            //组装vip标签
            List<PadFaceUserInfoNewVO> userInfoByUserId =
                    iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(padFaceSyncDataDTO.getProjectId()), padFaceSyncDataDTO.getAppUserIds());
            for (PadFaceUserInfoNewVO userInfoNewVO : userInfoByUserId) {
                if (userInfoNewVO.getUserLabel()==null){
                    padFaceSyncDataUserVO.setIsVip(0);
                }else {
                    padFaceSyncDataUserVO.setIsVip((Arrays.asList(userInfoNewVO.getUserLabel().split(",")).contains("1")?1:0));
                }
            }

            padFaceSyncDataUserVO.setStatus(status);
            // 用户是否欠物业费用 0是 1否
            padFaceSyncDataUserVO.setOutstandingAccounts("1");
            padFaceSyncDataUserVO.setHouseUserType("5");
            padFaceSyncDataUserVO.setStartTime("");
            padFaceSyncDataUserVO.setEndTime("");
            List<PadFaceSyncDataUserVO> list = new ArrayList<>();
            list.add(padFaceSyncDataUserVO);

            for (String deviceUnique : deviceUniques){
                Integer accountByRoomId = null;
                if (roomIds != null && !roomIds.isEmpty()) {
                    accountByRoomId = iPadFaceSyncDataServiceDao.getOverdueCountByRoomId(roomIds, deviceUnique);
                }
                if (accountByRoomId != null && accountByRoomId > 0) {
                    padFaceSyncDataUserVO.setOutstandingAccounts("0");
                    // 正常人员才会有欠费状态
                    if ("1".equals(padFaceSyncDataUserVO.getStatus())) {
                        padFaceSyncDataUserVO.setStatus("2");
                    }
                }
                PadPullCloudInfoPO padPullCloudInfoPO1 = new PadPullCloudInfoPO();
                padPullCloudInfoPO1.setDeviceUnique(deviceUnique);
                padPullCloudInfoPO1.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData1 = JSON.toJSONString(list);
                padPullCloudInfoPO1.setSyncData(syncData1);
                padPullCloudInfoPO1.setSyncType(2);
                padPullCloudInfoPO1.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO1.setDataType(1);
                padPullCloudInfoPO1.setSyncStatus(1);
                padPullCloudInfoPO1.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO1.setCreateTime(nowTime);
                padPullCloudInfoPO1.setUpdateTime(nowTime);
                iPadFaceSyncDataServiceDao.updatePadOrderByUser(list.get(0).getUserId(),deviceUnique);//清除当前设备,当前用户之前的1号指令
                padPullCloudInfoPOList.add(padPullCloudInfoPO1);
                padPullCloudInfoPOAllList.add(padPullCloudInfoPO1);

                if (!authsDoor.isEmpty()) {
                    PadPullCloudInfoPO padPullCloudInfoPO2 = new PadPullCloudInfoPO();
                    padPullCloudInfoPO2.setDeviceUnique(deviceUnique);
                    padPullCloudInfoPO2.setProjectId(padFaceSyncDataDTO.getProjectId());
                    String syncData2 = JSON.toJSONString(authsDoor);
                    padPullCloudInfoPO2.setSyncData(syncData2);
                    padPullCloudInfoPO2.setSyncType(2);
                    padPullCloudInfoPO2.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO2.setDataType(2);
                    padPullCloudInfoPO2.setSyncStatus(1);
                    padPullCloudInfoPO2.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO2.setCreateTime(nowTime);
                    padPullCloudInfoPO2.setUpdateTime(nowTime);
                    padPullCloudInfoPO2.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                    padPullCloudInfoPO2.setInstructionType(3);
                    padPullCloudInfoPOList.add(padPullCloudInfoPO2);
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO2);
                }

                if (!authsElevator.isEmpty()) {
                    PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
                    padPullCloudInfoPO3.setDeviceUnique(deviceUnique);
                    padPullCloudInfoPO3.setProjectId(padFaceSyncDataDTO.getProjectId());
                    String syncData3 = JSON.toJSONString(authsElevator);
                    padPullCloudInfoPO3.setSyncData(syncData3);
                    padPullCloudInfoPO3.setSyncType(2);
                    padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO3.setDataType(2);
                    padPullCloudInfoPO3.setSyncStatus(1);
                    padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO3.setCreateTime(nowTime);
                    padPullCloudInfoPO3.setUpdateTime(nowTime);
                    padPullCloudInfoPO3.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                    padPullCloudInfoPO3.setInstructionType(3);
                    padPullCloudInfoPOList.add(padPullCloudInfoPO3);
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO3);
                }
            }
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        } else if ("2".equals(padFaceSyncDataDTO.getOperateType()))
        { // 操作类型，"2"楼层映射表变更
            String deviceUniques = padFaceSyncDataDTO.getDeviceUniques();
            List<String> deviceUniqueList = StringHandlerUtil.splitStringList(deviceUniques);
            Map<String,List<PadFaceSyncDataElevatorFloorVO>> SyncDataMapList = new HashMap<>();
            for (String deviceUniqueOfElevator : deviceUniqueList){
                PadFaceSyncDataFloorVO elevatorFloorInfo = iPadFaceSyncDataServiceDao.getElevatorFloorInfo(deviceUniqueOfElevator);
                PadFaceSyncDataElevatorFloorVO padFaceSyncDataElevatorFloorVO = new PadFaceSyncDataElevatorFloorVO();
                padFaceSyncDataElevatorFloorVO.setFloorMapping(elevatorFloorInfo);
                padFaceSyncDataElevatorFloorVO.setDeviceUnique(deviceUniqueOfElevator);
                // 配置平板需要同步的数据
                List<String> buildIds = iPadFaceSyncDataServiceDao.getBuildIdsOfElevator(deviceUniqueOfElevator);
                List<String> padDeviceUniques = iPadFaceSyncDataServiceDao.getPadDeviceUniques(buildIds);
                if (padDeviceUniques == null || padDeviceUniques.isEmpty()) {
                    continue;
                }
                for (String padDeviceUnique : padDeviceUniques){
                    if (SyncDataMapList.get(padDeviceUnique) == null) {
                        List<PadFaceSyncDataElevatorFloorVO> list = new ArrayList<>();
                        list.add(padFaceSyncDataElevatorFloorVO);
                        SyncDataMapList.put(padDeviceUnique,list);
                    } else {
                        SyncDataMapList.get(padDeviceUnique).add(padFaceSyncDataElevatorFloorVO);
                    }
                }
            }
            if (SyncDataMapList.isEmpty()) {
                return 1;
            }
            // 组装插入表的数据
            SyncDataMapList.forEach((key, value) -> {
                PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                padPullCloudInfoPO.setDeviceUnique(key);
                padPullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData = JSON.toJSONString(value);
                padPullCloudInfoPO.setSyncData(syncData);
                padPullCloudInfoPO.setSyncType(2);
                padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO.setDataType(3);
                padPullCloudInfoPO.setSyncStatus(1);
                padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO.setCreateTime(nowTime);
                padPullCloudInfoPO.setUpdateTime(nowTime);
                padPullCloudInfoPO.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                padPullCloudInfoPO.setInstructionType(20);
                padPullCloudInfoPOList.add(padPullCloudInfoPO);
                padPullCloudInfoPOAllList.add(padPullCloudInfoPO);
            });
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        } else if ("3".equals(padFaceSyncDataDTO.getOperateType()))
        { // 操作类型，"3"访客人脸注册或删除访客
            List<String> passIdList = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getPassId());
            List<AppVisitorPassCodeRecordPO> appVisitorPassCodeRecordPOS = iPadFaceSyncDataServiceDao.getAppVisitorByPassId(passIdList,padFaceSyncDataDTO.getProjectId());
            if (appVisitorPassCodeRecordPOS == null || appVisitorPassCodeRecordPOS.isEmpty()) {
                return 1;
            }
            //查询用户的常用楼层和公共楼层
            List<PadFaceUserInfoNewVO> userInfo =
                    iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(padFaceSyncDataDTO.getAppUserIds()), padFaceSyncDataDTO.getProjectId());
            String commonFloor=null;
            String publicFloor=null;
            for (PadFaceUserInfoNewVO userInfoNewVO : userInfo) {
                commonFloor = userInfoNewVO.getCommonFloor();
                publicFloor = userInfoNewVO.getPublicFloor();
            }
            net.sf.json.JSONObject jsonCommonFloor=null;
            net.sf.json.JSONObject jsonPublicFloor=null;
            if (commonFloor!=null){
                jsonCommonFloor = net.sf.json.JSONObject.fromObject(commonFloor);
            }
            if (publicFloor!=null){
                jsonPublicFloor = net.sf.json.JSONObject.fromObject(publicFloor);
            }

            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
            Map<String,List<PadFaceSyncDataUserVO>> syncDataMapList = new HashMap<>();
            List<Map<String,Object>> authsDoor = new ArrayList<>();
            List<Map<String,Object>> authsElevator = new ArrayList<>();
            for (AppVisitorPassCodeRecordPO appVisitorPassCodeRecordPO : appVisitorPassCodeRecordPOS) {
                if (StringUtils.isBlank(appVisitorPassCodeRecordPO.getBuildId()) || StringUtils.isBlank(appVisitorPassCodeRecordPO.getVFaceId())
                        || StringUtils.isBlank(appVisitorPassCodeRecordPO.getUnitId())) {
                    continue;
                }
                // 同时要给到访客设备权限
                if ("1".equals(padFaceSyncDataDTO.getStatus())) {
                    // 门禁
                    List<AppDoorDevicesVO> doorDevices;
                    if (StringUtils.isNotBlank(appVisitorPassCodeRecordPO.getUserId())) {
                        doorDevices = iAppDeviceService.getDoorDevices(appVisitorPassCodeRecordPO.getUserId(), padFaceSyncDataDTO.getProjectId(), 1);
                    } else {
                        doorDevices = iPadFaceSyncDataServiceDao.getDoorDeviceByAddress(appVisitorPassCodeRecordPO);
                    }
                    if (doorDevices != null && !doorDevices.isEmpty()) {
                        Map<String, Object> authDoor = new HashMap<>();
                        List<Map<String, Object>> sysAuthDoor = new ArrayList<>();
                        authDoor.put("userId", appVisitorPassCodeRecordPO.getVFaceId());
                        authDoor.put("houseUserType", "4");
                        authDoor.put("startTime", sdf.format(appVisitorPassCodeRecordPO.getStartTime()));
                        authDoor.put("endTime", sdf.format(appVisitorPassCodeRecordPO.getEndTime()));
                        authDoor.put("deviceType", 1);
                        for (AppDoorDevicesVO door : doorDevices) {
                            // 业主可能存在多个楼栋或单元，找到访客地址对应的门禁再生成数据
                            DeviceEntranceBridgeInfoPO deviceEntranceBridgeInfoPO = iPadFaceSyncDataServiceDao.getEntranceBridge(door.getDeviceUnique());
                            if (deviceEntranceBridgeInfoPO == null) {
                                continue;
                            }
                            if (StringUtils.isNotBlank(deviceEntranceBridgeInfoPO.getUnitId()) && !deviceEntranceBridgeInfoPO.getUnitId().contains(appVisitorPassCodeRecordPO.getUnitId())) {
                                continue;
                            }
                            if (StringUtils.isNotBlank(deviceEntranceBridgeInfoPO.getBuildId()) && !deviceEntranceBridgeInfoPO.getBuildId().contains(appVisitorPassCodeRecordPO.getBuildId())) {
                                continue;
                            }
                            Map<String, Object> sysAuth = new HashMap<>();
                            sysAuth.put("auth", "8");
                            sysAuth.put("deviceUnique", door.getDeviceUnique());

                            if (commonFloor==null){
                                sysAuth.put("commonFloor","");
                            }else {
                                StringBuilder builder = new StringBuilder();


                                if (jsonCommonFloor.containsKey(door)){
                                    builder.append(jsonCommonFloor.get(door)).append(",");
                                }
                                sysAuth.put("commonFloor",( "".equals(builder+""))?"":builder.toString().substring(0,builder.length()-1));
                            }
                            if (publicFloor==null){
                                sysAuth.put("publicFloor","");
                            }else {
                                StringBuilder builderp = new StringBuilder();

                                if (jsonPublicFloor.containsKey(door)){
                                    builderp.append(jsonPublicFloor.get(door)).append(",");
                                }
                                sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));

                            }

                            sysAuthDoor.add(sysAuth);
                        }
                        authDoor.put("sysAuths", sysAuthDoor);
                        authsDoor.add(authDoor);
                    }

                    // 电梯
                    List<AppFloorDevicesVO> floorDevices;
                    if (StringUtils.isNotBlank(appVisitorPassCodeRecordPO.getUserId())) {
                        floorDevices = iAppDeviceService.getFloorDevices(appVisitorPassCodeRecordPO.getUserId(), padFaceSyncDataDTO.getProjectId(), 1);
                    } else {
                        floorDevices = iPadFaceSyncDataServiceDao.getFloorDeviceByAddress(appVisitorPassCodeRecordPO);
                    }
                    if (floorDevices != null && !floorDevices.isEmpty()) {
                        Map<String, Object> authElevator = new HashMap<>();
                        List<Map<String, Object>> sysAuthElevator = new ArrayList<>();
                        authElevator.put("userId", appVisitorPassCodeRecordPO.getVFaceId());
                        authElevator.put("houseUserType", "4");
                        authElevator.put("startTime", sdf.format(appVisitorPassCodeRecordPO.getStartTime()));
                        authElevator.put("endTime", sdf.format(appVisitorPassCodeRecordPO.getEndTime()));
                        authElevator.put("deviceType", 2);
                        for (AppFloorDevicesVO floor : floorDevices) {
                            // 业主可能存在多个楼栋或单元，找到访客地址对应的电梯再生成数据
                            DeviceElevatorBridgeInfoPO deviceElevatorBridgeInfoPO = iPadFaceSyncDataServiceDao.getElevatorBridge(floor.getDeviceUnique());
                            if (deviceElevatorBridgeInfoPO == null) {
                                continue;
                            }
                            if (!(deviceElevatorBridgeInfoPO.getBuildId().contains(appVisitorPassCodeRecordPO.getBuildId()) &&
                                    deviceElevatorBridgeInfoPO.getUnitId().contains(appVisitorPassCodeRecordPO.getUnitId()))) {
                                continue;
                            }
                            Map<String, Object> sysAuth = new HashMap<>();
                            // 业主可能存在多个房间，给到对应房间的楼层
                            sysAuth.put("auth", iPadFaceSyncDataServiceDao.getNaturalFloorByFloorNum(appVisitorPassCodeRecordPO.getFloorNum(), floor.getDeviceUnique()));
                            sysAuth.put("deviceUnique", floor.getDeviceUnique());
                            if (commonFloor==null){
                                sysAuth.put("commonFloor","");
                            }else {
                                StringBuilder builder = new StringBuilder();


                                if (jsonCommonFloor.containsKey(floor)){
                                    builder.append(jsonCommonFloor.get(floor)).append(",");
                                }
                                sysAuth.put("commonFloor",("".equals(builder+""))?"":builder.toString().substring(0,builder.length()-1));
                            }
                            if (publicFloor==null){
                                sysAuth.put("publicFloor","");
                            }else {
                                StringBuilder builderp = new StringBuilder();

                                if (jsonPublicFloor.containsKey(floor)){
                                    builderp.append(jsonPublicFloor.get(floor)).append(",");
                                }
                                sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));
                            }

                            sysAuthElevator.add(sysAuth);
                        }
                        authElevator.put("sysAuths", sysAuthElevator);
                        authsElevator.add(authElevator);
                    }
                }

                PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
                padFaceSyncDataUserVO.setUserName(appVisitorPassCodeRecordPO.getVisitorName() == null ? "" : appVisitorPassCodeRecordPO.getVisitorName());
                padFaceSyncDataUserVO.setUserId(appVisitorPassCodeRecordPO.getVFaceId());
                padFaceSyncDataUserVO.setImageUrl(appVisitorPassCodeRecordPO.getFacePicUrl());
                padFaceSyncDataUserVO.setStatus(padFaceSyncDataDTO.getStatus());

                // 用户是否欠物业费用 0是 1否
                padFaceSyncDataUserVO.setOutstandingAccounts("1");
                padFaceSyncDataUserVO.setHouseUserType("4"); // 4访客 5app住户
                padFaceSyncDataUserVO.setIsVip(0);
                padFaceSyncDataUserVO.setStartTime(sdf.format(appVisitorPassCodeRecordPO.getStartTime()));
                padFaceSyncDataUserVO.setEndTime(sdf.format(appVisitorPassCodeRecordPO.getEndTime()));
                List<String> buildIds = new ArrayList<>();
                buildIds.add(appVisitorPassCodeRecordPO.getBuildId());
                List<String> deviceUniques = iPadFaceSyncDataServiceDao.getPadDeviceUniques(buildIds);
                for (String deviceUnique : deviceUniques){
                    if (syncDataMapList.get(deviceUnique) == null) {
                        List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                        list.add(padFaceSyncDataUserVO);
                        syncDataMapList.put(deviceUnique,list);
                    } else {
                        syncDataMapList.get(deviceUnique).add(padFaceSyncDataUserVO);
                    }
                }
            }

            if (syncDataMapList.isEmpty()) {
                return 1;
            }
            // 组装插入表的数据
            syncDataMapList.forEach((key, value) -> {
                for (PadFaceSyncDataUserVO vo : value) {
                    List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                    list.add(vo);
                    PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                    padPullCloudInfoPO.setDeviceUnique(key);
                    padPullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                    String syncData = JSON.toJSONString(list);
                    padPullCloudInfoPO.setSyncData(syncData);
                    padPullCloudInfoPO.setSyncType(2);
                    padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO.setDataType(1);
                    padPullCloudInfoPO.setSyncStatus(1);
                    padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO.setCreateTime(nowTime);
                    padPullCloudInfoPO.setUpdateTime(nowTime);
                    padPullCloudInfoPO.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                    padPullCloudInfoPO.setInstructionType(4);
                    iPadFaceSyncDataServiceDao.updatePadOrderByUser(list.get(0).getUserId(),key);//清除当前设备,当前用户之前的1号指令
                    padPullCloudInfoPOList.add(padPullCloudInfoPO);
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO);
                }

                if (!authsDoor.isEmpty()) {
                    PadPullCloudInfoPO padPullCloudInfoPO2 = new PadPullCloudInfoPO();
                    padPullCloudInfoPO2.setDeviceUnique(key);
                    padPullCloudInfoPO2.setProjectId(padFaceSyncDataDTO.getProjectId());
                    String syncData2 = JSON.toJSONString(authsDoor);
                    padPullCloudInfoPO2.setSyncData(syncData2);
                    padPullCloudInfoPO2.setSyncType(2);
                    padPullCloudInfoPO2.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO2.setDataType(2);
                    padPullCloudInfoPO2.setSyncStatus(1);
                    padPullCloudInfoPO2.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO2.setCreateTime(nowTime);
                    padPullCloudInfoPO2.setUpdateTime(nowTime);
                    padPullCloudInfoPO2.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                    padPullCloudInfoPO2.setInstructionType(4);
                    padPullCloudInfoPOList.add(padPullCloudInfoPO2);
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO2);
                }

                if (!authsElevator.isEmpty()) {
                    //推送权限信息
                    //在推送设备权限指令时判断人脸识别设备是否绑定了群控器
                    List<PropertyDeviceCloudControllerEleVO> cloudElevatorList = new ArrayList<>();
                    List<String> padDeviceUniqueList = new ArrayList<>();
                    padDeviceUniqueList.add(key);
                    List<Map<String, Object>> deviceUniqueMapList = iPropertyPadDao.getBindDeviceUniqueByPad(padDeviceUniqueList);//绑定设备编号逗号分隔
                    if (deviceUniqueMapList.size() > 0 && deviceUniqueMapList.get(0).get("bindDeviceUnique") != null
                            && StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUniqueMapList.get(0).get("bindDeviceUnique").toString()) == 5) {//只有一条此刻,判断是否绑定了群控器
                        String[] bindDeviceUniqueS = deviceUniqueMapList.get(0).get("bindDeviceUnique").toString().split(",");//绑定设备
                        for (String bindDeviceUnique : bindDeviceUniqueS) {
                            //根据群控器查询出对应云电梯
                            PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO = new PropertyDeviceCloudControllerGetDTO();
                            propertyDeviceCloudControllerGetDTO.setProjectId(padFaceSyncDataDTO.getProjectId());
                            propertyDeviceCloudControllerGetDTO.setDeviceId(bindDeviceUnique.substring(bindDeviceUnique.length() - 4, bindDeviceUnique.length()));
                            PropertyDeviceCloudControllerGetVO vo = null;
                            try {
                                vo = iDeviceCloudControllerService.getOne(propertyDeviceCloudControllerGetDTO);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            for (PropertyDeviceCloudControllerEleVO controller : vo.getCloudElevatorList()) {//将群控器编号放回list中
                                controller.setDeviceUniqueContrroller(vo.getDeviceUnique());
                            }
                            //拼接所有云电梯
                            cloudElevatorList.addAll(vo.getCloudElevatorList());
                        }
                        //判断云电梯是否为绑定群控器控制,并替换云电梯的设备编号为群控器编号
                        for (Map<String, Object> mapUser : authsElevator) {
                            List<Map<String, Object>> sysAuths = (List<Map<String, Object>>) mapUser.get("sysAuths");
                            //存电梯对象的新容器
                            Map<String, Object> sMap = new HashMap<>();
                            //替换原sysAuths的新容器
                            List<Map<String, Object>> newSysAuths = new ArrayList<>();
                            //判断已遍历过的电梯对应群控机号是否已处理过
                            Set<String> deviceUniqueSet = new HashSet<>();
                            for (Map<String, Object> mapAuth : sysAuths) {//循环权限
                                //找出当前sysAuth对应的控制器信息
                                Optional<PropertyDeviceCloudControllerEleVO> optional = cloudElevatorList.stream().filter(vo -> vo.getDeviceUniqueElevator().equals(mapAuth.get("deviceUnique").toString())).findFirst();
                                PropertyDeviceCloudControllerEleVO controllerVo = optional.isPresent() ? optional.get() : null;
                                if (controllerVo != null) {//有当前群控器管控的云电梯时
                                    if (deviceUniqueSet.add(controllerVo.getDeviceUniqueContrroller())) {
                                        //第一次处理
                                        mapAuth.put("deviceUnique", controllerVo.getDeviceUniqueContrroller());
                                        sMap.put(controllerVo.getDeviceUniqueContrroller(), mapAuth);
                                    } else {
                                        Map<String, Object> repeatMap = (HashMap) sMap.get(controllerVo.getDeviceUniqueContrroller());
                                        //替换操作 mapAuth  / repeatMap
                                        String auth = StringHandlerUtil.duplicateEemoval(mapAuth.get("auth").toString() + "," + repeatMap.get("auth"));
                                        repeatMap.put("auth", auth);
                                    }
                                } else {//没有管控的直接无条件添加
                                    newSysAuths.add(mapAuth);
                                    continue;
                                }
                            }
                            for (String keys : sMap.keySet()) {
                                newSysAuths.add((HashMap) sMap.get(keys));
                            }
                            mapUser.put("sysAuths", newSysAuths);
                        }
                    }

                    PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
                    padPullCloudInfoPO3.setDeviceUnique(key);
                    padPullCloudInfoPO3.setProjectId(padFaceSyncDataDTO.getProjectId());
                    String syncData3 = JSON.toJSONString(authsElevator);
                    padPullCloudInfoPO3.setSyncData(syncData3);
                    padPullCloudInfoPO3.setSyncType(2);
                    padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO3.setDataType(2);
                    padPullCloudInfoPO3.setSyncStatus(1);
                    padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO3.setCreateTime(nowTime);
                    padPullCloudInfoPO3.setUpdateTime(nowTime);
                    padPullCloudInfoPO3.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                    padPullCloudInfoPO3.setInstructionType(4);
                    padPullCloudInfoPOList.add(padPullCloudInfoPO3);
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO3);
                }
            });
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        }
        //取得版本和iotkey
        ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOList.get(0).getDeviceUnique());
        //将增量数据发送iot到平板设备
        for (PadPullCloudInfoPO po : padPullCloudInfoPOList) {
            //过滤离线平板
            if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique())) && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                        "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                        po.getDeviceUnique(),"itlong",po.getSyncType().toString(),0,po.getSyncType().toString(),1);
                sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
            }
        }
        return 1;
    }

    /**
     * <desc>
     *      住户信息变更和楼层映射信息变更触发一卡通动态人脸识别同步数据
     * </desc>
     *
     * @param padFaceSyncDataDTO 人脸增量同步数据DTO
     * @return 0失败，1成功
     * @author wangzhi
     * @createDate 2019/03/19
     */
    private Integer userOrFloorSyncExecuteSmartCard(PadFaceSyncDataDTO padFaceSyncDataDTO) throws Exception {
        // 人脸注册那边是异步，这边5秒后再开始
        if(StringUtils.isBlank(padFaceSyncDataDTO.getSleepMark())){
            Thread.sleep(5000);
        }
        Date nowTime = new Date();
        List<SmartCardFacePullCloudInfoPO> smartCardFacePullCloudInfoPOList = new ArrayList<>();
        // 操作类型，"0"住户冻结、解冻 "5"修改用户标签及姓名
        if ("0".equals(padFaceSyncDataDTO.getOperateType()) || "5".equals(padFaceSyncDataDTO.getOperateType())) {
            List<String> appUserIds = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getAppUserIds());
            List<Map<String, Object>> syncDataListMap = new ArrayList<>();
            // 先以userId为单位拿到需要更新的数据，并组装数据
            for (String appUserId : appUserIds) {
                String facePicUrl = iPadFaceSyncDataServiceDao.getFacePicUrl(appUserId, padFaceSyncDataDTO.getProjectId());
                if (StringUtils.isBlank(facePicUrl)) {
                    continue;
                }
                //查询用户在项目下的标签及常用楼层信息
                Map<String,Object> resultMap = iPadFaceSyncDataServiceDao.getUserLabelInfo(appUserId, padFaceSyncDataDTO.getProjectId());
                String username = iPadFaceSyncDataServiceDao.getUsername(appUserId);
                Map<String, Object> map = new HashMap<>();
                map.put("userName", username == null ? "" : username);
                map.put("userId", appUserId);
                map.put("id", appUserId);
                map.put("imageUrl", facePicUrl);
                // 用户禁用启用状态 1正常 2禁用
                if (StringUtils.isNotBlank(padFaceSyncDataDTO.getStatus())) {
                    map.put("status", padFaceSyncDataDTO.getStatus());
                } else {
                    // 先判断用户项目冻结状态
                    map.put("status", "1".equals(iPadFaceSyncDataServiceDao.getUserProjectStatus(appUserId, padFaceSyncDataDTO.getProjectId())) ? "1" : "2");
                    // 用户未冻结，则判断用户禁用状态
                    if ("1".equals(map.get("status"))) {
                        map.put("status", "1".equals(iPadFaceSyncDataServiceDao.getUserStatus(appUserId)) ? "1" : "2");
                    }
                }
                map.put("houserType","5");
                map.put("startTime","");
                map.put("endTime","");
                if(resultMap!=null){
                    map.put("userLabel",(resultMap.get("userLabel")!=null && StringUtils.isNotEmpty(resultMap.get("userLabel")+""))?resultMap.get("userLabel"):"0");
                }
                syncDataListMap.add(map);

                // 组装插入表的数据
                SmartCardFacePullCloudInfoPO smartCardFacePullCloudInfoPO = new SmartCardFacePullCloudInfoPO();
                smartCardFacePullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData = JSON.toJSONString(syncDataListMap);
                smartCardFacePullCloudInfoPO.setSyncData(syncData);
                smartCardFacePullCloudInfoPO.setSyncType(2);
                smartCardFacePullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                smartCardFacePullCloudInfoPO.setDataType(1);
                smartCardFacePullCloudInfoPO.setSyncStatus(1);
                smartCardFacePullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                smartCardFacePullCloudInfoPO.setCreateTime(nowTime);
                smartCardFacePullCloudInfoPO.setUpdateTime(nowTime);
                smartCardFacePullCloudInfoPOList.add(smartCardFacePullCloudInfoPO);
            }
            if (syncDataListMap.isEmpty()) {
                return 1;
            }
            iPadFaceSyncDataServiceDao.batchSaveSmartCard(smartCardFacePullCloudInfoPOList);
        } else if ("1".equals(padFaceSyncDataDTO.getOperateType()) || "6".equals(padFaceSyncDataDTO.getOperateType())) { // 操作类型，"1"人脸注册 "6"住户分组禁用启用 及住户分组权限变更只组装权限指令
            List<Map<String, Object>> syncDataListMap = new ArrayList<>();
            String facePicUrl = iPadFaceSyncDataServiceDao.getFacePicUrl(padFaceSyncDataDTO.getAppUserIds(),padFaceSyncDataDTO.getProjectId());
            String username = iPadFaceSyncDataServiceDao.getUsername(padFaceSyncDataDTO.getAppUserIds());
            //查询用户在项目下的标签及常用楼层信息
            Map<String,Object> resultMap = iPadFaceSyncDataServiceDao.getUserLabelInfo(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId());
            // 同时要给到用户设备权限
            // 门禁
            List<AppDoorDevicesVO> doorDevices = iAppDeviceService.getDoorDevices(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId(), 1);
            List<Map<String,Object>> authsDoorElevator = new ArrayList<>();
            if (doorDevices != null && !doorDevices.isEmpty()) {
                Map<String, Object> authDoor = new HashMap<>();
                List<Map<String,Object>> sysAuthDoor = new ArrayList<>();
                authDoor.put("userId",padFaceSyncDataDTO.getAppUserIds());
                authDoor.put("id",padFaceSyncDataDTO.getAppUserIds());
                for (AppDoorDevicesVO door : doorDevices) {
                    Map<String,Object> sysAuth = new HashMap<>();
                    sysAuth.put("auth","8");
                    sysAuth.put("deviceUnique",door.getDeviceUnique());
                    sysAuth.put("deviceType",2);
                    if((StringUtils.isNotBlank(door.getDoorType()) && door.getDoorType().contains("3")) ||
                            (StringUtils.isNotBlank(door.getDoorType()) && door.getDoorType().contains("1,3"))){
                        sysAuth.put("isWippen","1");
                    }else{
                        sysAuth.put("isWippen","0");
                    }
                    sysAuthDoor.add(sysAuth);
                }
                authDoor.put("sysAuths",sysAuthDoor);
                authsDoorElevator.add(authDoor);
            }

            // 电梯
            List<AppFloorDevicesVO> floorDevices = iAppDeviceService.getFloorDevicesByNoStardard(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId(), 1);
//            List<Map<String,Object>> authsElevator = new ArrayList<>();
            if (floorDevices != null && !floorDevices.isEmpty()) {
                Map<String, Object> authElevator = new HashMap<>();
                List<Map<String,Object>> sysAuthElevator = new ArrayList<>();
                authElevator.put("userId",padFaceSyncDataDTO.getAppUserIds());
                authElevator.put("id",padFaceSyncDataDTO.getAppUserIds());
                for (AppFloorDevicesVO floor : floorDevices) {
                    Map<String,Object> sysAuth = new HashMap<>();
                    sysAuth.put("auth",floor.getLiveFloor());
                    sysAuth.put("mainFloor",floor.getMainFloor());
                    sysAuth.put("backFloor",floor.getBackFloor());
                    sysAuth.put("deviceUnique",floor.getDeviceUnique());
                    sysAuth.put("deviceType",1);
                    //处理用户在电梯设备中所设置的常用楼层
                    if(resultMap!=null && resultMap.get("userAllCommonFloor")!=null && StringUtils.isNotBlank(resultMap.get("userAllCommonFloor").toString())){
                        Map<String,Object> commanFloors = JsonUtil.toObject(resultMap.get("userAllCommonFloor").toString(),HashMap.class);
                        if(commanFloors.containsKey(floor.getDeviceUnique())){
                            if(StringUtils.isNotEmpty(floor.getLiveFloor()) && Arrays.asList(floor.getLiveFloor().split(",")).contains(commanFloors.get(floor.getDeviceUnique()).toString())){
                                sysAuth.put("commonFloor", commanFloors.get(floor.getDeviceUnique()).toString());
                            }else{
                                sysAuth.put("commonFloor", "");
                            }
                        }else{
                            sysAuth.put("commonFloor", "");
                        }
                    }else{
                        sysAuth.put("commonFloor", "");
                    }
                    sysAuthElevator.add(sysAuth);
                }
                authElevator.put("sysAuths",sysAuthElevator);
//                authsElevator.add(authElevator);
                authsDoorElevator.add(authElevator);
            }

            if("1".equals(padFaceSyncDataDTO.getOperateType())){
                // 用户信息
                Map<String,Object> map = new HashMap<>();
                map.put("userName",username == null ? "" : username);
                map.put("userId",padFaceSyncDataDTO.getAppUserIds());
                map.put("id",padFaceSyncDataDTO.getAppUserIds());
                map.put("imageUrl",facePicUrl);
                map.put("status","1");
                map.put("houserType","5");
                map.put("startTime","");
                map.put("endTime","");
                if(resultMap!=null){
                    map.put("userLabel",resultMap.get("userLabel")!=null?resultMap.get("userLabel"):"0");
                }
                syncDataListMap.add(map);

                // 组装插入表的数据
                SmartCardFacePullCloudInfoPO smartCardFacePullCloudInfoPO = new SmartCardFacePullCloudInfoPO();
                smartCardFacePullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData = JSON.toJSONString(syncDataListMap);
                smartCardFacePullCloudInfoPO.setSyncData(syncData);
                smartCardFacePullCloudInfoPO.setSyncType(2);
                smartCardFacePullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                smartCardFacePullCloudInfoPO.setDataType(1);
                smartCardFacePullCloudInfoPO.setSyncStatus(1);
                smartCardFacePullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                smartCardFacePullCloudInfoPO.setCreateTime(nowTime);
                smartCardFacePullCloudInfoPO.setUpdateTime(nowTime);
                smartCardFacePullCloudInfoPOList.add(smartCardFacePullCloudInfoPO);
            }
            if(doorDevices.size()==0 && floorDevices.size()==0){
                Map<String, Object> authElevator = new HashMap<>();
                List<Map<String,Object>> sysAuthElevator = new ArrayList<>();
                authElevator.put("userId",padFaceSyncDataDTO.getAppUserIds());
                authElevator.put("id",padFaceSyncDataDTO.getAppUserIds());
                authElevator.put("sysAuths",sysAuthElevator);
//                authsElevator.add(authElevator);
                authsDoorElevator.add(authElevator);
            }
            if (!authsDoorElevator.isEmpty()) {
                SmartCardFacePullCloudInfoPO smartCardFacePullCloudInfoPO2 = new SmartCardFacePullCloudInfoPO();
                smartCardFacePullCloudInfoPO2.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData2 = JSON.toJSONString(authsDoorElevator);
                smartCardFacePullCloudInfoPO2.setSyncData(syncData2);
                smartCardFacePullCloudInfoPO2.setSyncType(2);
                smartCardFacePullCloudInfoPO2.setSyncSerialNo(LogicIdUtil.bussinessId());
                smartCardFacePullCloudInfoPO2.setDataType(2);
                smartCardFacePullCloudInfoPO2.setSyncStatus(1);
                smartCardFacePullCloudInfoPO2.setStatus(DataStatusEnum.NORMAL.getType());
                smartCardFacePullCloudInfoPO2.setCreateTime(nowTime);
                smartCardFacePullCloudInfoPO2.setUpdateTime(nowTime);
                smartCardFacePullCloudInfoPOList.add(smartCardFacePullCloudInfoPO2);
            }
            if(smartCardFacePullCloudInfoPOList!=null && smartCardFacePullCloudInfoPOList.size()>0){
                iPadFaceSyncDataServiceDao.batchSaveSmartCard(smartCardFacePullCloudInfoPOList);
            }
        } else if ("2".equals(padFaceSyncDataDTO.getOperateType())) { // 操作类型，"2"楼层映射表变更
            List<Map<String, Object>> syncDataListMap = new ArrayList<>();
            String deviceUniques = padFaceSyncDataDTO.getDeviceUniques();
            List<String> deviceUniqueList = StringHandlerUtil.splitStringList(deviceUniques);
            for (String deviceUniqueOfElevator : deviceUniqueList){
                Map<String,Object> map = new HashMap<>();
                PadFaceSyncDataFloorVO elevatorFloorInfo = iPadFaceSyncDataServiceDao.getElevatorFloorInfo(deviceUniqueOfElevator);
                map.put("deviceUnique",deviceUniqueOfElevator);
                map.put("logicalFloor",elevatorFloorInfo.getLogicalFloor());
                map.put("naturalFloor",elevatorFloorInfo.getNaturalFloor());
                map.put("terminalFloor",elevatorFloorInfo.getTerminalFloor());
                map.put("floorNum",elevatorFloorInfo.getFloorNum());
                syncDataListMap.add(map);
            }
            if (syncDataListMap.isEmpty()) {
                return 1;
            }

            // 组装插入表的数据
            SmartCardFacePullCloudInfoPO smartCardFacePullCloudInfoPO = new SmartCardFacePullCloudInfoPO();
            smartCardFacePullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
            String syncData = JSON.toJSONString(syncDataListMap);
            smartCardFacePullCloudInfoPO.setSyncData(syncData);
            smartCardFacePullCloudInfoPO.setSyncType(2);
            smartCardFacePullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
            smartCardFacePullCloudInfoPO.setDataType(3);
            smartCardFacePullCloudInfoPO.setSyncStatus(1);
            smartCardFacePullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            smartCardFacePullCloudInfoPO.setCreateTime(nowTime);
            smartCardFacePullCloudInfoPO.setUpdateTime(nowTime);
            smartCardFacePullCloudInfoPOList.add(smartCardFacePullCloudInfoPO);
            iPadFaceSyncDataServiceDao.batchSaveSmartCard(smartCardFacePullCloudInfoPOList);
        } else if ("3".equals(padFaceSyncDataDTO.getOperateType())) { // 操作类型，"3"访客人脸注册或删除访客
            //LOG.info("【人脸识别系统开始处理访客数据】" );
            List<Map<String, Object>> syncDataListMap = new ArrayList<>();
            List<String> passIdList = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getPassId());
            List<AppVisitorPassCodeRecordPO> appVisitorPassCodeRecordPOS = iPadFaceSyncDataServiceDao.getAppVisitorByPassId(passIdList,padFaceSyncDataDTO.getProjectId());
            if (appVisitorPassCodeRecordPOS == null || appVisitorPassCodeRecordPOS.isEmpty()) {
                //LOG.info("【人脸识别系统根据passId查询数据为空】" );
                return 1;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
            List<Map<String,Object>> authsDoorElevator = new ArrayList<>();
//            List<Map<String,Object>> authsElevator = new ArrayList<>();
            for (AppVisitorPassCodeRecordPO appVisitorPassCodeRecordPO : appVisitorPassCodeRecordPOS) {
                if (StringUtils.isBlank(appVisitorPassCodeRecordPO.getBuildId()) || StringUtils.isBlank(appVisitorPassCodeRecordPO.getVFaceId())
                        || StringUtils.isBlank(appVisitorPassCodeRecordPO.getUnitId())) {
                    continue;
                }
                // 同时要给到用户设备权限
                // 门禁
                List<AppDoorDevicesVO> doorDevices;
                if (StringUtils.isNotBlank(appVisitorPassCodeRecordPO.getUserId())) {
                    doorDevices = iAppDeviceService.getDoorDevices(appVisitorPassCodeRecordPO.getUserId(),padFaceSyncDataDTO.getProjectId(),1);
                } else {
                    doorDevices = iPadFaceSyncDataServiceDao.getDoorDeviceByAddress(appVisitorPassCodeRecordPO);
                }
                if (doorDevices != null && !doorDevices.isEmpty()) {
                    Map<String, Object> authDoor = new HashMap<>();
                    List<Map<String,Object>> sysAuthDoor = new ArrayList<>();
                    authDoor.put("userId",appVisitorPassCodeRecordPO.getVFaceId());
                    authDoor.put("id",appVisitorPassCodeRecordPO.getPassId());
                    for (AppDoorDevicesVO door : doorDevices) {
                        // 业主可能存在多个楼栋或单元，找到访客地址对应的门禁再生成数据
                        DeviceEntranceBridgeInfoPO deviceEntranceBridgeInfoPO = iPadFaceSyncDataServiceDao.getEntranceBridge(door.getDeviceUnique());
                        if (deviceEntranceBridgeInfoPO == null) {
                            continue;
                        }
                        if (StringUtils.isNotBlank(deviceEntranceBridgeInfoPO.getUnitId()) && !deviceEntranceBridgeInfoPO.getUnitId().contains(appVisitorPassCodeRecordPO.getUnitId())) {
                            continue;
                        }
                        if (StringUtils.isNotBlank(deviceEntranceBridgeInfoPO.getBuildId()) && !deviceEntranceBridgeInfoPO.getBuildId().contains(appVisitorPassCodeRecordPO.getBuildId())) {
                            continue;
                        }
                        Map<String,Object> sysAuth = new HashMap<>();
                        sysAuth.put("auth","8");
                        sysAuth.put("deviceUnique",door.getDeviceUnique());
                        sysAuth.put("deviceType",2);
                        if((StringUtils.isNotBlank(door.getDoorType()) && door.getDoorType().contains("3")) ||
                                (StringUtils.isNotBlank(door.getDoorType()) && door.getDoorType().contains("1,3"))){
                            sysAuth.put("isWippen","1");
                        }else{
                            sysAuth.put("isWippen","0");
                        }
                        sysAuthDoor.add(sysAuth);
                    }
                    authDoor.put("sysAuths",sysAuthDoor);
                    authsDoorElevator.add(authDoor);
                }

                // 电梯
                List<AppFloorDevicesVO> floorDevices;
                if (StringUtils.isNotBlank(appVisitorPassCodeRecordPO.getUserId())) {
                    floorDevices = iAppDeviceService.getFloorDevices(appVisitorPassCodeRecordPO.getUserId(), padFaceSyncDataDTO.getProjectId(), 1);
                } else {
                    floorDevices = iPadFaceSyncDataServiceDao.getFloorDeviceByAddress(appVisitorPassCodeRecordPO);
                }
                if (floorDevices != null && !floorDevices.isEmpty()) {
                    Map<String, Object> authElevator = new HashMap<>();
                    List<Map<String,Object>> sysAuthElevator = new ArrayList<>();
                    authElevator.put("userId",appVisitorPassCodeRecordPO.getVFaceId());
                    authElevator.put("id",appVisitorPassCodeRecordPO.getPassId());
                    for (AppFloorDevicesVO floor : floorDevices) {
                        // 业主可能存在多个楼栋或单元，找到访客地址对应的电梯再生成数据
                        DeviceElevatorBridgeInfoPO deviceElevatorBridgeInfoPO = iPadFaceSyncDataServiceDao.getElevatorBridge(floor.getDeviceUnique());
                        if (deviceElevatorBridgeInfoPO == null) {
                            continue;
                        }
                        if (!(deviceElevatorBridgeInfoPO.getBuildId().contains(appVisitorPassCodeRecordPO.getBuildId()) &&
                                deviceElevatorBridgeInfoPO.getUnitId().contains(appVisitorPassCodeRecordPO.getUnitId()))) {
                            continue;
                        }
                        Map<String,Object> sysAuth = new HashMap<>();
                        //根据roomId查询房屋正背门属性
                        String liftDoorType = iPadFaceSyncDataServiceDao.getLiftDoorTypeByRoomId(appVisitorPassCodeRecordPO.getRoomId());
                        // 业主可能存在多个房间，给到对应房间的楼层
                        sysAuth.put("auth",iPadFaceSyncDataServiceDao.getNaturalFloorByFloorNum(appVisitorPassCodeRecordPO.getFloorNum(), floor.getDeviceUnique()));
                        if(StringUtils.isNotBlank(liftDoorType) && liftDoorType.equals("1")){
                            sysAuth.put("mainFloor",iPadFaceSyncDataServiceDao.getNaturalFloorByFloorNum(appVisitorPassCodeRecordPO.getFloorNum(), floor.getDeviceUnique()));
                        }else{
                            sysAuth.put("backFloor",iPadFaceSyncDataServiceDao.getNaturalFloorByFloorNum(appVisitorPassCodeRecordPO.getFloorNum(), floor.getDeviceUnique()));
                        }
                        sysAuth.put("deviceUnique",floor.getDeviceUnique());
                        sysAuth.put("deviceType",1);
                        sysAuthElevator.add(sysAuth);
                    }
                    authElevator.put("sysAuths",sysAuthElevator);
//                    authsElevator.add(authElevator);
                    authsDoorElevator.add(authElevator);
                }

                // 用户信息
                Map<String,Object> map = new HashMap<>();
                map.put("userName",appVisitorPassCodeRecordPO.getVisitorName() == null ? "" : appVisitorPassCodeRecordPO.getVisitorName());
                map.put("userId",appVisitorPassCodeRecordPO.getVFaceId());
                map.put("id",appVisitorPassCodeRecordPO.getPassId());
                map.put("imageUrl",appVisitorPassCodeRecordPO.getFacePicUrl());
                map.put("status","1".equals(padFaceSyncDataDTO.getStatus()) ? "1" : "2");
                map.put("houserType","4"); // 4访客 5住户
                map.put("startTime",sdf.format(appVisitorPassCodeRecordPO.getStartTime()));
                map.put("endTime",sdf.format(appVisitorPassCodeRecordPO.getEndTime()));
                syncDataListMap.add(map);
            }
            if (syncDataListMap.isEmpty()) {
                //LOG.info("【人脸识别系统根据syncDataListMap数据为空】" );
                return 1;
            }

            //LOG.info("人脸识别系统保存用户信息数据" + syncDataListMap);
            for (Map<String, Object> map : syncDataListMap) {
                List<Map<String, Object>> listMap = new ArrayList<>();
                listMap.add(map);
                // 组装插入表的数据
                SmartCardFacePullCloudInfoPO smartCardFacePullCloudInfoPO = new SmartCardFacePullCloudInfoPO();
                smartCardFacePullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData = JSON.toJSONString(listMap);
                smartCardFacePullCloudInfoPO.setSyncData(syncData);
                smartCardFacePullCloudInfoPO.setSyncType(2);
                smartCardFacePullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                smartCardFacePullCloudInfoPO.setDataType(1);
                smartCardFacePullCloudInfoPO.setSyncStatus(1);
                smartCardFacePullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                smartCardFacePullCloudInfoPO.setCreateTime(nowTime);
                smartCardFacePullCloudInfoPO.setUpdateTime(nowTime);
                smartCardFacePullCloudInfoPOList.add(smartCardFacePullCloudInfoPO);
            }

            //LOG.info("人脸识别系统保存设备权限数据" + authsDoorElevator);
            if (!authsDoorElevator.isEmpty()) {
                SmartCardFacePullCloudInfoPO smartCardFacePullCloudInfoPO2 = new SmartCardFacePullCloudInfoPO();
                smartCardFacePullCloudInfoPO2.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData2 = JSON.toJSONString(authsDoorElevator);
                smartCardFacePullCloudInfoPO2.setSyncData(syncData2);
                smartCardFacePullCloudInfoPO2.setSyncType(2);
                smartCardFacePullCloudInfoPO2.setSyncSerialNo(LogicIdUtil.bussinessId());
                smartCardFacePullCloudInfoPO2.setDataType(2);
                smartCardFacePullCloudInfoPO2.setSyncStatus(1);
                smartCardFacePullCloudInfoPO2.setStatus(DataStatusEnum.NORMAL.getType());
                smartCardFacePullCloudInfoPO2.setCreateTime(nowTime);
                smartCardFacePullCloudInfoPO2.setUpdateTime(nowTime);
                smartCardFacePullCloudInfoPOList.add(smartCardFacePullCloudInfoPO2);
            }

            Integer intRes = iPadFaceSyncDataServiceDao.batchSaveSmartCard(smartCardFacePullCloudInfoPOList);
            //LOG.info("人脸识别系统保存数据SQL返回：" + intRes);
        } else if ("4".equals(padFaceSyncDataDTO.getOperateType())) { // 操作类型，"4"云群控器添加和修改
            List<String> deviceUniqueControllerList = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getDeviceUniques());
            List<Map<String, Object>> syncDataListMap = iPadFaceSyncDataServiceDao.getControllerElevator(deviceUniqueControllerList);
            if (syncDataListMap == null || syncDataListMap.isEmpty()) {
                return 1;
            }

            // 组装插入表的数据
            SmartCardFacePullCloudInfoPO smartCardFacePullCloudInfoPO = new SmartCardFacePullCloudInfoPO();
            smartCardFacePullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
            String syncData = JSON.toJSONString(syncDataListMap);
            smartCardFacePullCloudInfoPO.setSyncData(syncData);
            smartCardFacePullCloudInfoPO.setSyncType(2);
            smartCardFacePullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
            smartCardFacePullCloudInfoPO.setDataType(4);
            smartCardFacePullCloudInfoPO.setSyncStatus(1);
            smartCardFacePullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            smartCardFacePullCloudInfoPO.setCreateTime(nowTime);
            smartCardFacePullCloudInfoPO.setUpdateTime(nowTime);
            smartCardFacePullCloudInfoPOList.add(smartCardFacePullCloudInfoPO);
            iPadFaceSyncDataServiceDao.batchSaveSmartCard(smartCardFacePullCloudInfoPOList);
        }
        return 1;
    }

//    public static void main(String[] args) throws Exception{
//        String LYKZ_URL = "47.96.84.248";
//        String LYKZ_ACCOUNT_SID = "47b4180d12fa4cf0850b210d6c741999";
//        String LYKZ_ACCOUNT_TOKEN = "a844f9ddeb65d05a6995a7a6621e00c2";
//        String LYKZ_PORT = "38080";
//        String LYKZ_SOFT_VERSION = "2015-06-30";
//        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
//        String nowTime = sd.format(new Date());
//        String sigParameter = Md5EncryptUtil.md5(String.format("%s%s%s",LYKZ_ACCOUNT_SID,LYKZ_ACCOUNT_TOKEN,nowTime)).toUpperCase();
//        String host = "http://"+LYKZ_URL+":"+LYKZ_PORT+"/ucsrtc-rest-api/"+LYKZ_SOFT_VERSION+"/Accounts/"+LYKZ_ACCOUNT_SID;
//        String path = "/ClientsByMobile";
//        String method = "GET";
//
//        final Base64.Encoder encoder = Base64.getEncoder();
//        final String context = String.format("%s%s%s",LYKZ_ACCOUNT_SID,":",nowTime);
//        final byte[] textByte = context.getBytes("UTF-8");
//        //编码
//        final String authorization = encoder.encodeToString(textByte);
//
//        Map<String, String> headers = new HashMap<>();
//        headers.put("Authorization", authorization);
//        headers.put("Accept", "application/json;");
//        headers.put("Content-Type", "application/json;charset=utf-8");
//
//        Map<String, String> querys = new HashMap<>();
//        querys.put("sig",sigParameter);
//        querys.put("appId","d68fa3a4a854496f9445628d7eed61ad");
//        querys.put("mobile","13692194709");
//
//        HttpResponse response = HttpProtocolUtil.doGet(host, path, method, headers, querys);
//
//
//        if (response != null && response.getEntity() != null) {
//            Map<String, Object> jsonToMap = JsonUtil.JsonToMap(EntityUtils.toString(response.getEntity()));
//            if (jsonToMap != null && !jsonToMap.isEmpty()){
//                Map<String, Object> jsonToMapResp = JsonUtil.JsonToMap(jsonToMap.get("resp").toString());
//                if(jsonToMapResp != null && !jsonToMapResp.isEmpty()){
//                    String respCode = jsonToMapResp.get("respCode").toString();
//                    if(respCode.equals("000000")){
//                        String client = jsonToMapResp.get("client").toString();
//                        Map<String, Object> jsonToMapClient = JsonUtil.JsonToMap(client);
//                        Map<String,String> resultMap = new HashMap<>();
//                        resultMap.put("clientNumber",jsonToMapClient.get("clientNumber").toString());
//                        resultMap.put("clientPwd",jsonToMapClient.get("clientPwd").toString());
//                        resultMap.put("loginToken",jsonToMapClient.get("loginToken").toString());
//                        resultMap.put("createDate",jsonToMapClient.get("createDate").toString());
//                        resultMap.put("lykzUserId",jsonToMapClient.get("userId").toString());
//                        resultMap.put("mobile",jsonToMapClient.get("mobile").toString());
//                        System.out.println(resultMap.toString());
//                    }else{
//                    }
//
//                }
//            }
//        }
//    }

    /**
     * <desc>
     *      平板增量获取变更数据接口
     * </desc>
     *
     * @param padDeviceUnique 平板deviceUnique
     * @return 变更数据
     * @author wangzhi
     * @createDate 2019/01/18
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public List<PadIncrementUpdateGetVO> getIncrementUpdate(String padDeviceUnique) throws Exception {
        List<PadIncrementUpdateGetVO> padIncrementUpdateGetVOS = iPadFaceSyncDataServiceDao.getIncrementUpdate(padDeviceUnique);
        if (padIncrementUpdateGetVOS != null && !padIncrementUpdateGetVOS.isEmpty()) {
            List<String> syncSerialNos = new ArrayList<>();
            for (PadIncrementUpdateGetVO padIncrementUpdateGetVO : padIncrementUpdateGetVOS){
                syncSerialNos.add(padIncrementUpdateGetVO.getSyncSerialNo());
            }
            // 同步状态设置为同步中
            Map<String, Object> map = new HashMap<>();
            map.put("syncSerialNos",syncSerialNos);
            map.put("syncStatus",2); // 同步状态标志 1.待同步；2.同步中;3.同步结束
            iPadFaceSyncDataServiceDao.setSyncStatus(map);
        }
        return padIncrementUpdateGetVOS;
    }

    /**
     * <desc>
     *      修改同步状态为同步结束
     * </desc>
     *
     * @param syncSerialNo 同步流水号，多个用英文逗号相连
     * @return 0失败，1成功
     * @author wangzhi
     * @createDate 2019/01/18
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updateSyncStatus(String syncSerialNo) throws Exception {
        List<String> syncSerialNos = StringHandlerUtil.splitStringList(syncSerialNo);
        // 同步状态设置为同步结束
        Map<String, Object> map = new HashMap<>();
        map.put("syncSerialNos",syncSerialNos);
        map.put("syncStatus",3); // 同步状态标志 1.待同步；2.同步中;3.同步结束
        return iPadFaceSyncDataServiceDao.setSyncStatus(map);
    }

    /**
     * <desc>
     *      修改同步状态为同步结束
     * </desc>
     *
     * @param syncSerialNo 同步流水号，多个用英文逗号相连
     * @param msg 失败原因
     * @return 0失败，1成功
     * @author wangzhi
     * @createDate 2019/01/18
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer reportUpdateResult(String syncSerialNo,String msg) throws Exception {
        List<String> syncSerialNos = StringHandlerUtil.splitStringList(syncSerialNo);
        // 同步状态设置为同步结束
        Map<String, Object> map = new HashMap<>();
        map.put("syncSerialNo",syncSerialNo);
        map.put("msg",msg);
        map.put("syncStatus",4); // 同步状态标志 1.待同步；2.同步中;3.同步结束;4.同步失败
        return iPadFaceSyncDataServiceDao.reportUpdateResult(map);
    }

    /**
     * <desc>
     *      平板上电获取全量数据
     * </desc>
     *
     * @param deviceUnique
     * @param type 1电梯 2门禁
     * @return
     * @author Jiaqi.X
     * @createDate 2019/01/23
     */
    @Override
    public Map<String,Object> pullFull(String bandDeviceUnique,String deviceUnique,Integer type){
        //获取平板的地址
        List<Map<String,Object>> builds = iPadFaceSyncDataServiceDao.getAddressByDeviceUnique(deviceUnique);
        Map<String,Object> data = new HashMap<>();
        //根据平板达到设备类型查询 拥有该设备权限并且有人脸的用户，然后再与地址权限用户进行去重处理
        List<String> userList = new ArrayList<>();
        List<PadFaceUserInfoVO> vosByGroup = null;
        if(type==1){
            vosByGroup = iPadFaceSyncDataServiceDao.getUserInfosByElevatorGroup(Integer.valueOf(StringHandlerUtil.getDeviceIdByDeviceUnique(bandDeviceUnique)),StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique));
        }else if(type==2){
            vosByGroup = iPadFaceSyncDataServiceDao.getUserInfosByEntranceGroup(StringHandlerUtil.splitString(bandDeviceUnique),StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique));
        }
        if(builds.size() > 1 ){
            //多楼栋
            List<String> bs = new ArrayList<>();
            builds.forEach(build->{
                bs.add(build.get("buildId").toString());
            });
            List<PadFaceUserInfoVO> vos = iPadFaceSyncDataServiceDao.getUserInfosByBuilds(bs, StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique));
            if(vosByGroup!=null){
                vos.addAll(vosByGroup);
            }
            List<PadFaceUserInfoVO> visitors = iPadFaceSyncDataServiceDao.getVisitorFaceInfosByBuilds(bs,
            DateUtil.fomatDate(new Date(), DateUtil.DATE_FORMAT_TYPE1));
            for(int i=vos.size()-1;i>=0;i--){
                if(userList.contains(vos.get(i).getUserId())){
                    vos.remove(i);
                }else{
                    userList.add(vos.get(i).getUserId());
                }
                if(vos.get(i).getStatus() == PadUserStatusEnum.NORMAL.getType() && vos.get(i).getOutstandingAccounts()!=null  && vos.get(i).getOutstandingAccounts() > 0){
                    vos.get(i).setStatus(2);
                }
                //组装vip标识符
                if (vos.get(i).getUserLabel()==null){
                    vos.get(i).setIsVip(0);
                }else {
                    vos.get(i).setIsVip(Arrays.asList(vos.get(i).getUserLabel().split(",")).contains("1")?1:0);
                }
            }
            vos.addAll(visitors);
            data.put("userInfos",vos);
        }else if(builds.size() == 1){
            //多单元
            String[] unit = StringHandlerUtil.splitString(builds.get(0).get("unitId").toString());
            List<PadFaceUserInfoVO> vos = iPadFaceSyncDataServiceDao.getUserInfosByUnits(unit, StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique));
            List<PadFaceUserInfoVO> visitors = iPadFaceSyncDataServiceDao.getVisitorFaceInfosByUnits(unit,
                    DateUtil.fomatDate(new Date(), DateUtil.DATE_FORMAT_TYPE1));
            if(vosByGroup!=null){
                vos.addAll(vosByGroup);
            }
            for(int i=vos.size()-1;i>=0;i--){
                if(userList.contains(vos.get(i).getUserId())){
                    vos.remove(i);
                }else{
                    userList.add(vos.get(i).getUserId());
                }
                if(vos.get(i).getStatus() == PadUserStatusEnum.NORMAL.getType() && vos.get(i).getOutstandingAccounts()!=null && vos.get(i).getOutstandingAccounts() > 0){
                    vos.get(i).setStatus(2);
                }
                //组装vip标识符
                if (vos.get(i).getUserLabel()==null){
                    vos.get(i).setIsVip(0);
                }else {
                    vos.get(i).setIsVip(Arrays.asList(vos.get(i).getUserLabel().split(",")).contains("1")?1:0);
                }
            }

            vos.addAll(visitors);
            data.put("userInfos",vos);
        }
        if(type == 1) {
            List<Map<String,Object>> floors = new ArrayList<>();
            for (String strBandDeviceUnique : bandDeviceUnique.split(",")) {
                //获取电梯起始楼层及结束楼层
                Map<String,Object> minAndMaxFloor = iPadFaceSyncDataServiceDao.getMinAndMaxFloor(strBandDeviceUnique);
                Integer startFloor = minAndMaxFloor==null || minAndMaxFloor.get("minFloor") == null ? null : Double.valueOf(minAndMaxFloor.get("minFloor").toString()).intValue();
                Integer endFloor = minAndMaxFloor==null || minAndMaxFloor.get("maxFloor") == null ? null : Double.valueOf(minAndMaxFloor.get("maxFloor").toString()).intValue();
                Map<String,Object> floor = new HashMap<>();
                floor.put("floorMapping",iPadFaceSyncDataServiceDao.getFloorsByDeviceUnique(strBandDeviceUnique,startFloor,endFloor));
                floor.put("deviceUnique",strBandDeviceUnique);
                floors.add(floor);
            }
            data.put("floors", floors);
        }
        iPadFaceSyncDataServiceDao.deletePullDataByDeviceUnique(deviceUnique);
        return data;
    }

    /**
     * <desc>
     *      生成人脸指令
     * </desc>
     *
     * @param deviceUnique  人脸识别仪编号
     * @param userInfo   用户信息
     * @return
     * @author Qiang.S
     * @createDate 2019/12/24
     */
    @Override
    public void createUserInstruct(String deviceUnique,String userInfo,Integer InstructionType,Integer sourceSystem){
        JSONArray userInfoJsonArray = JSONArray.parseArray(userInfo.toString());
        List<Map<String, Object>> syncDataListMap = new ArrayList<>();
        List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
        Date nowTime = new Date();
        for (int i=0;i<userInfoJsonArray.size();i++) {
            JSONObject job = userInfoJsonArray.getJSONObject(i);
            String appUserId = job.get("userId").toString();
            String houserType = job.get("houserType").toString();
            if (houserType != null && "5".equals(houserType)) {//住户
                String facePicUrl = iPadFaceSyncDataServiceDao.getFacePicUrl(appUserId, deviceUnique.substring(0, 8));
                if (StringUtils.isBlank(facePicUrl)) {
                    continue;
                }
                String username = iPadFaceSyncDataServiceDao.getUsername(appUserId);
                List<String> roomIds = iPadFaceSyncDataServiceDao.getAppUserRoomId(appUserId, deviceUnique.substring(0, 8));
                Integer accountByRoomId = null;
                if (roomIds != null && !roomIds.isEmpty()) {
                    accountByRoomId = iPadFaceSyncDataServiceDao.getOverdueCountByRoomId(roomIds, deviceUnique);
                }

                Map<String, Object> map = new HashMap<>();
                map.put("userName", username == null ? "" : username);
                map.put("houserType", houserType); // 4访客 5住户
                map.put("userId", appUserId);
                map.put("imageUrl", facePicUrl);
                // 用户禁用启用状态 1正常 5禁用 4冻结 2欠费
                // 先判断用户项目冻结状态
                map.put("status", "1".equals(iPadFaceSyncDataServiceDao.getUserProjectStatus(appUserId, deviceUnique.substring(0, 8))) ? "1" : "4");
                // 用户未冻结，则判断用户禁用状态
                if ("1".equals(map.get("status"))) {
                    map.put("status", "1".equals(iPadFaceSyncDataServiceDao.getUserStatus(appUserId)) ? "1" : "5");
                }
                // 用户是否欠物业费用 0是 1否 2019/02/14 下午与有为沟通后，废弃此字段，合在上面status字段中
                map.put("outstandingAccounts", "1");
                if (accountByRoomId != null && accountByRoomId > 0) {
                    map.put("outstandingAccounts", "0");
                    // 正常人员才会有欠费状态
                    if ("1".equals(map.get("status"))) {
                        map.put("status", "2");
                    }
                }
                //组装vip标签
                List<PadFaceUserInfoNewVO> userInfoByUserId =
                        iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(deviceUnique.substring(0, 8)), appUserId);
                for (PadFaceUserInfoNewVO userInfoNewVO : userInfoByUserId) {
                    if (userInfoNewVO.getUserLabel()==null){
                        map.put("isVip","0");
                    }else {
                        map.put("isVip",(Arrays.asList(userInfoNewVO.getUserLabel().split(",")).contains("1")?1:0));
                    }
                }

                syncDataListMap.add(map);
            } else if (houserType != null && "4".equals(houserType)) {//访客
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
                List<String> faceIdList = StringHandlerUtil.splitStringList(appUserId);
                List<AppVisitorPassCodeRecordPO> appVisitorPassCodeRecordPOS = iPadFaceSyncDataServiceDao.getAppVisitorByFaceId(faceIdList, deviceUnique.substring(0, 8));
                for (AppVisitorPassCodeRecordPO appVisitorPassCodeRecordPO : appVisitorPassCodeRecordPOS) {
                    // 用户信息
                    Map<String, Object> map = new HashMap<>();
                    map.put("userName", appVisitorPassCodeRecordPO.getVisitorName() == null ? "" : appVisitorPassCodeRecordPO.getVisitorName());
                    map.put("userId", appVisitorPassCodeRecordPO.getVFaceId());
                    map.put("imageUrl", appVisitorPassCodeRecordPO.getFacePicUrl());
                    map.put("isVip","0");
                    map.put("outstandingAccounts", "1");
                    map.put("status", appVisitorPassCodeRecordPO.getStatus());
                    map.put("houserType", houserType); // 4访客 5住户
                    map.put("startTime", sdf.format(appVisitorPassCodeRecordPO.getStartTime()));
                    map.put("endTime", sdf.format(appVisitorPassCodeRecordPO.getEndTime()));
                    syncDataListMap.add(map);
                }
            }
        }
        // 组装插入表的数据,分开存入
        for (Map map : syncDataListMap) {
            List<PadFaceSyncDataUserVO> list = new ArrayList<>();
            PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
            padFaceSyncDataUserVO.setUserName(map.get("userName").toString());
            padFaceSyncDataUserVO.setUserId(map.get("userId").toString());
            padFaceSyncDataUserVO.setImageUrl(map.get("imageUrl").toString());
            padFaceSyncDataUserVO.setStatus(map.get("status").toString());
            padFaceSyncDataUserVO.setOutstandingAccounts(map.get("outstandingAccounts").toString());
            padFaceSyncDataUserVO.setHouseUserType(map.get("houserType").toString());
            padFaceSyncDataUserVO.setStartTime(map.get("startTime") == null ? "":map.get("startTime").toString());
            padFaceSyncDataUserVO.setEndTime(map.get("endTime") == null ? "":map.get("endTime").toString());
            List<PadFaceUserInfoNewVO> userInfoByUserId =
                    iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(deviceUnique.substring(0, 8)), padFaceSyncDataUserVO.getUserId());
            for (PadFaceUserInfoNewVO userInfoNewVO : userInfoByUserId) {
                if (userInfoNewVO.getUserLabel()==null){
                    padFaceSyncDataUserVO.setIsVip(0);
                }else {
                    padFaceSyncDataUserVO.setIsVip(Arrays.asList(userInfoNewVO.getUserLabel().split(",")).contains("1")?1:0);
                }
            }
            list.add(padFaceSyncDataUserVO);
            PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
            padPullCloudInfoPO.setDeviceUnique(deviceUnique);
            padPullCloudInfoPO.setProjectId(deviceUnique.substring(0, 8));


            String syncData = JSON.toJSONString(list);
            padPullCloudInfoPO.setSyncData(syncData);
            padPullCloudInfoPO.setSyncType(2);
            padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO.setDataType(1);
            padPullCloudInfoPO.setSyncStatus(1);
            padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO.setCreateTime(nowTime);
            padPullCloudInfoPO.setUpdateTime(nowTime);
            if (map.get("houserType") !=null){
                padPullCloudInfoPO.setSourceSystem("4".equals(map.get("houserType").toString()) ? 4:5);
            }
            padPullCloudInfoPO.setInstructionType(0);
            iPadFaceSyncDataServiceDao.updatePadOrderByUser(list.get(0).getUserId(),deviceUnique);//清除当前设备,当前用户之前的1号指令
            padPullCloudInfoPOList.add(padPullCloudInfoPO);
        }
        if (padPullCloudInfoPOList.size() > 0) {
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        }
    }

    /**
     * <desc>
     *      处理绑定普通门禁设备平板指令
     * </desc>
     *
     * @param appFaceRecognitionDeviceAuthDTO  处理绑定普通门禁平板指令入参
     * @return
     * @author Qiang.S
     * @createDate 2020/03/09
     */
    @Override
    public void padDeviceAuth(AppFaceRecognitionDeviceAuthDTO appFaceRecognitionDeviceAuthDTO) throws Exception{
        Thread.sleep(3000);
        Set<String> padDeviceUniques = new HashSet<>();
        List<String> padDeviceList = new ArrayList<>();
        //此MAP保存平板所绑定设备的类型 key为deviceUnique value为设备类型 1电梯 2门禁
        Map<String,String> map = new HashMap<>();
        List<PadPullCloudInfoPO> padPullCloudInfoPOAllList = new ArrayList<>();
        //门禁变动的集合
        List<String> entranceModifyList = new ArrayList<>();
        List<String> elevatorModifyList = new ArrayList<>();
        entranceModifyList.addAll(appFaceRecognitionDeviceAuthDTO.getDeleteDeviceUnique());
        entranceModifyList.addAll(appFaceRecognitionDeviceAuthDTO.getAddDeviceUnique());
        elevatorModifyList.addAll(appFaceRecognitionDeviceAuthDTO.getDeleteElevatorDeviceUnique());
        elevatorModifyList.addAll(appFaceRecognitionDeviceAuthDTO.getAddElevatorDeviceUnique());
        List<String> cloudEntraceList = new ArrayList<>();
        if(entranceModifyList!=null && entranceModifyList.size()>0){
            //云联动器集合
            cloudEntraceList = iPadFaceSyncDataServiceDao.getEntranceTypeByDeviceUnqiue(entranceModifyList);
        }
        Map<String,Object> elevatorListByRoleIdMap = appFaceRecognitionDeviceAuthDTO.getElevatorListByRoleIdMap();
        //查询门禁相关的平板设备
        if (entranceModifyList.size() > 0) {
            padDeviceList = iPadFaceSyncDataServiceDao.getPadDeviceUniqueByBindId(entranceModifyList);
            for(String padDeviceUnique : padDeviceList){
                map.put(padDeviceUnique,"2");
            }
            padDeviceUniques.addAll(padDeviceList);
        }
        //查询电梯相关的平板设备
        if (elevatorModifyList.size() > 0) {
            padDeviceList = iPadFaceSyncDataServiceDao.getPadDeviceUniqueByBindId(elevatorModifyList);
            for(String padDeviceUnique : padDeviceList){
                map.put(padDeviceUnique,"1");
            }
            padDeviceUniques.addAll(padDeviceList);
        }

        List<Map<String,Object>> authsDoor = new ArrayList<>();
        //根据平板设备编号循环
        if (padDeviceUniques.size() > 0) {//有绑定的
            for (String userId : appFaceRecognitionDeviceAuthDTO.getUserIdList()) {
                //查询用户的常用楼层和公共楼层
                List<PadFaceUserInfoNewVO> userInfo =
                        iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(userId), appFaceRecognitionDeviceAuthDTO.getProjectId());
                String commonFloor=null;
                String publicFloor=null;
                for (PadFaceUserInfoNewVO userInfoNewVO : userInfo) {
                    commonFloor = userInfoNewVO.getCommonFloor();
                    publicFloor = userInfoNewVO.getPublicFloor();
                }
                net.sf.json.JSONObject jsonCommonFloor=null;
                net.sf.json.JSONObject jsonPublicFloor=null;
                if (commonFloor!=null){
                    jsonCommonFloor = net.sf.json.JSONObject.fromObject(commonFloor);
                }
                if (publicFloor!=null){
                    jsonPublicFloor = net.sf.json.JSONObject.fromObject(publicFloor);
                }
                //处理门禁
                if(appFaceRecognitionDeviceAuthDTO.getDeviceType()==2) {
                    List<String> doorList = iPadFaceSyncDataServiceDao.getEntranceListByNotInRoleIdAndUserId("",userId);
                    Map<String, Object> authDoor = new HashMap<>();
                    List<Map<String,Object>> sysAuthDoor = new ArrayList<>();
                    authDoor.put("userId",userId);
                    authDoor.put("houseUserType","5");
                    authDoor.put("startTime","");
                    authDoor.put("endTime","");
                    authDoor.put("deviceType",3);
                    for (String entranceDeviceUnique : doorList) {
                        Map<String,Object> sysAuth = new HashMap<>();
                        //判断是否为联动器
                        sysAuth.put("auth","8");
                        sysAuth.put("deviceUnique",entranceDeviceUnique);
                        if(cloudEntraceList.contains(entranceDeviceUnique)){
                            if (commonFloor==null){
                                sysAuth.put("commonFloor","");
                            }else {
                                StringBuilder builder = new StringBuilder();


                                if (jsonCommonFloor.containsKey(entranceDeviceUnique)){
                                    builder.append(jsonCommonFloor.get(entranceDeviceUnique)).append(",");
                                }
                                sysAuth.put("commonFloor",builder.toString().substring(0,builder.length()-1));
                            }
                            if (publicFloor==null){
                                sysAuth.put("publicFloor","");
                            }else {
                                StringBuilder builderp = new StringBuilder();

                                if (jsonPublicFloor.containsKey(entranceDeviceUnique)){
                                    builderp.append(jsonPublicFloor.get(entranceDeviceUnique)).append(",");
                                }
                                sysAuth.put("publicFloor",builderp.toString().substring(0,builderp.length()-1));
                            }
                        }
                        sysAuthDoor.add(sysAuth);
                    }
                    authDoor.put("sysAuths",sysAuthDoor);
                    authsDoor.add(authDoor);
                }else if(appFaceRecognitionDeviceAuthDTO.getDeviceType()==1){
                    //处理电梯
                    List<AppFloorDevicesVO> floors = iAppDeviceService.getFloorDevices(userId, appFaceRecognitionDeviceAuthDTO.getProjectId(), 1);
                    Map<String, Object> authElevator = new HashMap<>();
                    List<Map<String,Object>> sysAuthElevator = new ArrayList<>();
                    authElevator.put("userId",userId);
                    authElevator.put("houseUserType","5");
                    authElevator.put("startTime","");
                    authElevator.put("endTime","");
                    authElevator.put("deviceType",2);
                    for (AppFloorDevicesVO floor : floors) {
                        Map<String,Object> sysAuth = new HashMap<>();
                        sysAuth.put("auth",floor.getLiveFloor());
                        sysAuth.put("deviceUnique",floor.getDeviceUnique());
                        if (commonFloor==null){
                            sysAuth.put("commonFloor","");
                        }else {
                            StringBuilder builder = new StringBuilder();


                            if (jsonCommonFloor.containsKey(floor)){
                                builder.append(jsonCommonFloor.get(floor)).append(",");
                            }
                            sysAuth.put("commonFloor",("".equals(builder+""))?"":(builder.toString().substring(0,(builder.length()-1))));

                        }
                        if (publicFloor==null){
                            sysAuth.put("publicFloor","");
                        }else {
                            StringBuilder builderp = new StringBuilder();

                            if (jsonPublicFloor.containsKey(floor)){
                                builderp.append(jsonPublicFloor.get(floor)).append(",");
                            }
                            sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));

                        }
                        sysAuthElevator.add(sysAuth);
                    }
                    authElevator.put("sysAuths",sysAuthElevator);
                    authsDoor.add(authElevator);
                }
            }
        }
        Date nowTime = new Date();
        for (String padDeviceUnique : padDeviceUniques) {
            PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
            padPullCloudInfoPO.setDeviceUnique(padDeviceUnique);
            padPullCloudInfoPO.setProjectId(StringHandlerUtil.getProjectIdByDeviceUnique(padDeviceUnique));
            String syncData2 = JSON.toJSONString(authsDoor);
            padPullCloudInfoPO.setSyncData(syncData2);
            padPullCloudInfoPO.setSyncType(2);
            padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO.setDataType(2);
            padPullCloudInfoPO.setSyncStatus(1);
            padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO.setCreateTime(nowTime);
            padPullCloudInfoPO.setUpdateTime(nowTime);
            //9:住户角色组信息设备授权
            padPullCloudInfoPO.setInstructionType(9);
            //2物业后台
            padPullCloudInfoPO.setSourceSystem(2);
            padPullCloudInfoPOAllList.add(padPullCloudInfoPO);

            //添加类型为1的人脸相关数据
            for (String userId : appFaceRecognitionDeviceAuthDTO.getUserIdList()) {
                //查询用户的常用楼层和公共楼层
                List<PadFaceUserInfoNewVO> userInfo =
                        iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(userId), appFaceRecognitionDeviceAuthDTO.getProjectId());
                PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
                padPullCloudInfoPO3.setDeviceUnique(padDeviceUnique);
                padPullCloudInfoPO3.setProjectId(appFaceRecognitionDeviceAuthDTO.getProjectId());
                if (userInfo.get(0).getUserLabel()==null){
                    userInfo.get(0).setIsVip(0);
                }else {
                    userInfo.get(0).setIsVip(Arrays.asList(userInfo.get(0).getUserLabel().split(",")).contains("1")?1:0);
                }
                userInfo.get(0).setStatus(1);
                List<PadFaceUserInfoNewVO> listVo1 = new ArrayList<>();
                String syncData1 = JSON.toJSONString(userInfo);
                padPullCloudInfoPO3.setSyncData(syncData1);
                padPullCloudInfoPO3.setSyncType(2);
                padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO3.setDataType(1);
                padPullCloudInfoPO3.setSyncStatus(1);
                padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO3.setCreateTime(nowTime);
                padPullCloudInfoPO3.setUpdateTime(nowTime);
                //10:住户角色组信息人员分配
                padPullCloudInfoPO.setInstructionType(10);
                //2物业后台
                padPullCloudInfoPO.setSourceSystem(2);
                padPullCloudInfoPOAllList.add(padPullCloudInfoPO3);
            }



        }
        if (padPullCloudInfoPOAllList.size() > 0) {
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOAllList);
            //取得版本和iotkey
            ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOAllList.get(0).getDeviceUnique());
            //将增量数据发送iot到平板设备
            for (PadPullCloudInfoPO po : padPullCloudInfoPOAllList) {
                //过滤离线平板
                if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique())) && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(),"itlong",po.getSyncType().toString(),0,po.getSyncType().toString(),1);
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        }
    }

    /**
     * <desc>
     *      处理绑定普通门禁用户平板指令
     * </desc>
     *
     * @param appFaceRecognitionDeviceAuthDTO  处理绑定普通门禁平板指令入参
     * @return
     * @author Qiang.S
     * @createDate 2020/03/10
     */
    @Override
    public void padUserAuth(AppFaceRecognitionDeviceAuthDTO appFaceRecognitionDeviceAuthDTO) throws Exception{
        if(StringUtils.isEmpty(appFaceRecognitionDeviceAuthDTO.getSleepMark())){
            Thread.sleep(4000);
        }
        List<String> padDeviceUniques = new ArrayList<>();
        //此MAP保存平板所绑定设备的类型 key为deviceUnique value为设备类型 1电梯 2门禁
        Map<String,String> map = new HashMap<>();
        List<PadPullCloudInfoPO> padPullCloudInfoPOAllList = new ArrayList<>();
        List<String> listEntranceTotal = appFaceRecognitionDeviceAuthDTO.getDeviceUniqueListByRoleId();
        List<String> cloudEntraceList = new ArrayList<>();
        if(listEntranceTotal!=null && listEntranceTotal.size()>0){
            //云联动器集合
            cloudEntraceList = iPadFaceSyncDataServiceDao.getEntranceTypeByDeviceUnqiue(listEntranceTotal);
            //处理门禁
            List<String> padDeviceList = iPadFaceSyncDataServiceDao.getPadDeviceUniqueByBindId(listEntranceTotal);
            for(String padDeviceUnique : padDeviceList){
                map.put(padDeviceUnique,"2");
            }
            padDeviceUniques.addAll(padDeviceList);
        }
        List<String> listElevator = appFaceRecognitionDeviceAuthDTO.getDeviceUniqueByElevatorArr();

        //处理电梯
        List<String> deviceUniqueByElevatorArr = new ArrayList<>();
        if (listElevator != null && listElevator.size() > 0) {
            List<String> padDeviceListByElevator = iPadFaceSyncDataServiceDao.getPadDeviceUniqueByBindId(listElevator);
            for(String padDeviceUnique : padDeviceListByElevator){
                map.put(padDeviceUnique,"1");
            }
            padDeviceUniques.addAll(padDeviceListByElevator);
        }

        List<PadFaceUserInfoNewVO> vosAddUsers = new ArrayList<>();
        List<PadFaceUserInfoNewVO> vosDeleteUsers = new ArrayList<>();
        if (appFaceRecognitionDeviceAuthDTO.getAddUser()!=null && appFaceRecognitionDeviceAuthDTO.getAddUser().size() > 0) {
            //根据用户编号查询用户信息
            vosAddUsers = iPadFaceSyncDataServiceDao.getUserInfoByUserId(appFaceRecognitionDeviceAuthDTO.getAddUser(),appFaceRecognitionDeviceAuthDTO.getProjectId());
        }
        if (appFaceRecognitionDeviceAuthDTO.getDeleteUser()!=null &&appFaceRecognitionDeviceAuthDTO.getDeleteUser().size() > 0) {
            //根据用户编号查询用户信息
            vosDeleteUsers = iPadFaceSyncDataServiceDao.getUserInfoByUserId(appFaceRecognitionDeviceAuthDTO.getDeleteUser(),appFaceRecognitionDeviceAuthDTO.getProjectId());
        }

        if (padDeviceUniques.size() > 0) {//平板数据和用户数据都有编辑指令
            Date nowTime = new Date();
            for (String padDeviceUnique : padDeviceUniques) {
                for (PadFaceUserInfoNewVO voAddUser : vosAddUsers) {

                    //查询用户的常用楼层和公共楼层
                    List<PadFaceUserInfoNewVO> userInfo =
                            iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(voAddUser.getUserId()), appFaceRecognitionDeviceAuthDTO.getProjectId());
                    String commonFloor=null;
                    String publicFloor=null;
                    for (PadFaceUserInfoNewVO userInfoNewVO : userInfo) {
                        commonFloor = userInfoNewVO.getCommonFloor();
                        publicFloor = userInfoNewVO.getPublicFloor();
                    }
                    Map jsonCommonFloor=null;
                    Map jsonPublicFloor=null;
                    if (commonFloor!=null){
                        jsonCommonFloor = JSON.parseObject(commonFloor, HashMap.class);
                    }
                    if (publicFloor!=null){
                        jsonPublicFloor =  JSON.parseObject(publicFloor, HashMap.class);
                    }

                    PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                    padPullCloudInfoPO.setDeviceUnique(padDeviceUnique);
                    padPullCloudInfoPO.setProjectId(appFaceRecognitionDeviceAuthDTO.getProjectId());
                    //组装vip
                    if (voAddUser.getUserLabel()==null){
                        voAddUser.setIsVip(0);
                    }else {
                        voAddUser.setIsVip(Arrays.asList(voAddUser.getUserLabel().split(",")).contains("1")?1:0);
                    }
                    voAddUser.setStatus(1);
                    List<PadFaceUserInfoNewVO> listVo = new ArrayList<>();
                    listVo.add(voAddUser);
                    String syncData = JSON.toJSONString(listVo);
                    padPullCloudInfoPO.setSyncData(syncData);
                    padPullCloudInfoPO.setSyncType(2);
                    padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO.setDataType(1);
                    padPullCloudInfoPO.setSyncStatus(1);
                    padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO.setCreateTime(nowTime);
                    padPullCloudInfoPO.setUpdateTime(nowTime);
                    //10:住户角色组信息人员分配
                    padPullCloudInfoPO.setInstructionType(10);
                    //2物业后台
                    padPullCloudInfoPO.setSourceSystem(2);
                    iPadFaceSyncDataServiceDao.updatePadOrderByUser(listVo.get(0).getUserId(),padDeviceUnique);//清除当前设备,当前用户之前的1号指令

                    if("2".equals(map.get(padDeviceUnique))){
                        //此处处理门禁相关逻辑
                        List<String> doorList = appFaceRecognitionDeviceAuthDTO.getDeviceUniqueListByRoleId();
                        Map<String, Object> authDoor = new HashMap<>();
                        List<Map<String,Object>> authsDoor = new ArrayList<>();
                        List<Map<String, Object>> sysAuthDoor = new ArrayList<>();
                        authDoor.put("userId", voAddUser.getUserId());
                        authDoor.put("houseUserType", "5");
                        authDoor.put("startTime", "");
                        authDoor.put("endTime", "");
                        authDoor.put("deviceType", 3);//普通门禁用3
                        for (String door : doorList) {
                            Map<String, Object> sysAuth = new HashMap<>();
                            sysAuth.put("auth", "8");
                            sysAuth.put("deviceUnique", door);
                            if(cloudEntraceList.contains(door)) {
                                if (commonFloor == null) {
                                    sysAuth.put("commonFloor", "");
                                } else {
                                    StringBuilder builder = new StringBuilder();


                                    if (jsonCommonFloor.containsKey(door)) {
                                        builder.append(jsonCommonFloor.get(door)).append(",");
                                    }
                                    sysAuth.put("commonFloor", builder.toString().substring(0, builder.length() - 1));
                                }
                                if (publicFloor == null) {
                                    sysAuth.put("publicFloor", "");
                                } else {
                                    StringBuilder builderp = new StringBuilder();

                                    if (jsonPublicFloor.containsKey(door)) {
                                        builderp.append(jsonPublicFloor.get(door)).append(",");
                                    }
                                    sysAuth.put("publicFloor", builderp.toString().substring(0, builderp.length() - 1));
                                }
                            }
                            sysAuthDoor.add(sysAuth);
                        }
                        authDoor.put("sysAuths", sysAuthDoor);
                        authsDoor.add(authDoor);

                        if (!authsDoor.isEmpty()) {
                            PadPullCloudInfoPO padPullCloudInfoPO2 = new PadPullCloudInfoPO();
                            padPullCloudInfoPO2.setDeviceUnique(padDeviceUnique);
                            padPullCloudInfoPO2.setProjectId(appFaceRecognitionDeviceAuthDTO.getProjectId());
                            String syncData2 = JSON.toJSONString(authsDoor);
                            padPullCloudInfoPO2.setSyncData(syncData2);
                            padPullCloudInfoPO2.setSyncType(2);
                            padPullCloudInfoPO2.setSyncSerialNo(LogicIdUtil.bussinessId());
                            padPullCloudInfoPO2.setDataType(2);
                            padPullCloudInfoPO2.setSyncStatus(1);
                            padPullCloudInfoPO2.setStatus(DataStatusEnum.NORMAL.getType());
                            padPullCloudInfoPO2.setCreateTime(nowTime);
                            padPullCloudInfoPO2.setUpdateTime(nowTime);
                            //10:住户角色组信息人员分配
                            padPullCloudInfoPO2.setInstructionType(10);
                            //2物业后台
                            padPullCloudInfoPO2.setSourceSystem(2);
                            padPullCloudInfoPOAllList.add(padPullCloudInfoPO2);
                        }
                    }
                    if("1".equals(map.get(padDeviceUnique))){
                        //此处处理电梯相关逻辑
                        AppElevatorAuthVO elevatorAuthVO = appFaceRecognitionDeviceAuthDTO.getElevatorAuthVO();
                        Map<String, Object> authElevator = new HashMap<>();
                        List<Map<String,Object>> authsElevator = new ArrayList<>();
                        List<Map<String, Object>> sysAuthElevator = new ArrayList<>();
                        authElevator.put("userId", voAddUser.getUserId());
                        authElevator.put("houseUserType", "5");
                        authElevator.put("startTime", "");
                        authElevator.put("endTime", "");
                        authElevator.put("deviceType", 1);//普通门禁用3
                        for (AppElevatorInfoVO elevatorInfoVO : elevatorAuthVO.getElevatorAuth()) {
                            Map<String, Object> sysAuth = new HashMap<>();
                            sysAuth.put("auth", elevatorInfoVO.getLiveFloor());
                            sysAuth.put("deviceUnique", appFaceRecognitionDeviceAuthDTO.getProjectId()+1+elevatorInfoVO.getDeviceId());
                            if (commonFloor==null){
                                sysAuth.put("commonFloor","");
                            }else {
                                StringBuilder builder = new StringBuilder();


                                if (jsonCommonFloor.containsKey(appFaceRecognitionDeviceAuthDTO.getProjectId()+1+elevatorInfoVO.getDeviceId())){
                                    builder.append(jsonCommonFloor.get(appFaceRecognitionDeviceAuthDTO.getProjectId()+1+elevatorInfoVO.getDeviceId())).append(",");
                                }
                                sysAuth.put("commonFloor",("".equals(builder+""))?"":(builder.toString().substring(0,(builder.length()-1))));

                            }
                            if (publicFloor==null){
                                sysAuth.put("publicFloor","");
                            }else {
                                StringBuilder builderp = new StringBuilder();

                                if (jsonPublicFloor.containsKey(appFaceRecognitionDeviceAuthDTO.getProjectId()+1+elevatorInfoVO.getDeviceId())){
                                    builderp.append(jsonPublicFloor.get(appFaceRecognitionDeviceAuthDTO.getProjectId()+1+elevatorInfoVO.getDeviceId())).append(",");
                                }
                                sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));

                            }
                            sysAuthElevator.add(sysAuth);
                        }
                        authElevator.put("sysAuths", sysAuthElevator);
                        authsElevator.add(authElevator);

                        if (!authsElevator.isEmpty()) {
                            PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
                            padPullCloudInfoPO3.setDeviceUnique(padDeviceUnique);
                            padPullCloudInfoPO3.setProjectId(appFaceRecognitionDeviceAuthDTO.getProjectId());
                            String syncData3 = JSON.toJSONString(authsElevator);
                            padPullCloudInfoPO3.setSyncData(syncData3);
                            padPullCloudInfoPO3.setSyncType(2);
                            padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
                            padPullCloudInfoPO3.setDataType(2);
                            padPullCloudInfoPO3.setSyncStatus(1);
                            padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
                            padPullCloudInfoPO3.setCreateTime(nowTime);
                            padPullCloudInfoPO3.setUpdateTime(nowTime);
                            //10:住户角色组信息人员分配
                            padPullCloudInfoPO3.setInstructionType(10);
                            //2物业后台
                            padPullCloudInfoPO3.setSourceSystem(2);
                            padPullCloudInfoPOAllList.add(padPullCloudInfoPO3);
                        }
                        padPullCloudInfoPOAllList.add(padPullCloudInfoPO);
                    }
                    PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
                    padPullCloudInfoPO3.setDeviceUnique(padDeviceUnique);
                    padPullCloudInfoPO3.setProjectId(appFaceRecognitionDeviceAuthDTO.getProjectId());
                    if (voAddUser.getUserLabel()==null){
                        voAddUser.setIsVip(0);
                    }else {
                        voAddUser.setIsVip(Arrays.asList(voAddUser.getUserLabel().split(",")).contains("1")?1:0);
                    }
                    voAddUser.setStatus(1);
                    List<PadFaceUserInfoNewVO> listVo1 = new ArrayList<>();
                    listVo1.add(voAddUser);
                    String syncData1 = JSON.toJSONString(listVo1);
                    padPullCloudInfoPO3.setSyncData(syncData1);
                    padPullCloudInfoPO3.setSyncType(2);
                    padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO3.setDataType(1);
                    padPullCloudInfoPO3.setSyncStatus(1);
                    padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO3.setCreateTime(nowTime);
                    padPullCloudInfoPO3.setUpdateTime(nowTime);
                    //10:住户角色组信息人员分配
                    padPullCloudInfoPO.setInstructionType(10);
                    //2物业后台
                    padPullCloudInfoPO.setSourceSystem(2);
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO3);
                }

                for (PadFaceUserInfoNewVO voDeleteUser : vosDeleteUsers) {
                    PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                    padPullCloudInfoPO.setDeviceUnique(padDeviceUnique);
                    padPullCloudInfoPO.setProjectId(appFaceRecognitionDeviceAuthDTO.getProjectId());
                    if (voDeleteUser.getUserLabel()==null){
                        voDeleteUser.setIsVip(0);
                    }else {
                        voDeleteUser.setIsVip(Arrays.asList(voDeleteUser.getUserLabel().split(",")).contains("1")?1:0);
                    }
                    voDeleteUser.setStatus(3);
                    List<PadFaceUserInfoNewVO> listVo = new ArrayList<>();
                    listVo.add(voDeleteUser);
                    String syncData = JSON.toJSONString(listVo);
                    padPullCloudInfoPO.setSyncData(syncData);
                    padPullCloudInfoPO.setSyncType(2);
                    padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO.setDataType(1);
                    padPullCloudInfoPO.setSyncStatus(1);
                    padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO.setCreateTime(nowTime);
                    padPullCloudInfoPO.setUpdateTime(nowTime);
                    //10:住户角色组信息人员分配
                    padPullCloudInfoPO.setInstructionType(10);
                    //2物业后台
                    padPullCloudInfoPO.setSourceSystem(2);
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO);
                }
            }
        }
        if (padPullCloudInfoPOAllList.size() > 0) {
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOAllList);
            //取得版本和iotkey
            ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOAllList.get(0).getDeviceUnique());
            //将增量数据发送iot到平板设备
            for (PadPullCloudInfoPO po : padPullCloudInfoPOAllList) {
                //过滤离线平板
                if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique())) && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(),"itlong",po.getSyncType().toString(),0,po.getSyncType().toString(),1);
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        }
    }

    /**
     * <desc>
     *      处理启用禁用角色平板指令
     * </desc>
     *
     * @param appFaceRecognitionDeviceAuthDTO  处理启用禁用角色平板指令入参
     * @return
     * @author Qiang.S
     * @createDate 2020/04/01
     */
    @Override
    public void padRoleStatusBussiness(AppFaceRecognitionDeviceAuthDTO appFaceRecognitionDeviceAuthDTO) throws Exception{
        Thread.sleep(3000);
        Set<String> padDeviceUniques = new HashSet<>();
        Map<String,Object> elevatorListByRoleIdMap = appFaceRecognitionDeviceAuthDTO.getElevatorListByRoleIdMap();
        List<String> entranceListByRole = appFaceRecognitionDeviceAuthDTO.getDeviceUniqueListByRoleId();
        //此MAP保存平板所绑定设备的类型 key为deviceUnique value为设备类型 1电梯 2门禁
        Map<String,String> map = new HashMap<>();
        List<PadPullCloudInfoPO> padPullCloudInfoPOAllList = new ArrayList<>();
        //处理门禁
        if (entranceListByRole != null && entranceListByRole.size() > 0) {
            List<String> padDeviceList = iPadFaceSyncDataServiceDao.getPadDeviceUniqueByBindId(appFaceRecognitionDeviceAuthDTO.getDeviceUniqueListByRoleId());
            for(String padDeviceUnique : padDeviceList){
                map.put(padDeviceUnique,"2");
            }
            padDeviceUniques.addAll(padDeviceList);
        }
        //处理电梯
        List<String> deviceUniqueByElevatorArr = new ArrayList<>();
        if (elevatorListByRoleIdMap != null && elevatorListByRoleIdMap.size() > 0) {
            deviceUniqueByElevatorArr = (List<String>) elevatorListByRoleIdMap.get("deviceUniqueArr");
            List<String> padDeviceListByElevator = iPadFaceSyncDataServiceDao.getPadDeviceUniqueByBindId(deviceUniqueByElevatorArr);
            for(String padDeviceUnique : padDeviceListByElevator){
                map.put(padDeviceUnique,"1");
            }
            padDeviceUniques.addAll(padDeviceListByElevator);
        }
        List<PadFaceUserInfoNewVO> vosUsers = new ArrayList<>();
        if (appFaceRecognitionDeviceAuthDTO.getUserIdList() != null && appFaceRecognitionDeviceAuthDTO.getUserIdList().size() > 0) {
            //根据用户编号查询用户信息
            vosUsers = iPadFaceSyncDataServiceDao.getUserInfoByUserId(appFaceRecognitionDeviceAuthDTO.getUserIdList(),appFaceRecognitionDeviceAuthDTO.getProjectId());
        }
        //TODO 查出本组内的人员的所有门禁和电梯的权限机号 再判断平板所绑定的机号在所有权限中是否有 若有即使禁用也直接跳过不推送禁用指令 如是启用则需新增电梯权限于指令

        if (padDeviceUniques.size() > 0 && vosUsers.size() > 0) {//平板数据和用户数据都有编辑指令
            Date nowTime = new Date();
            for (String padDeviceUnique : padDeviceUniques) {
                boolean mark = false;
                for (PadFaceUserInfoNewVO voUser : vosUsers) {

                    //查询用户的常用楼层和公共楼层
                    List<PadFaceUserInfoNewVO> userInfo =
                            iPadFaceSyncDataServiceDao.getUserInfoByUserId(Arrays.asList(voUser.getUserId()), appFaceRecognitionDeviceAuthDTO.getProjectId());
                    String commonFloor=null;
                    String publicFloor=null;
                    for (PadFaceUserInfoNewVO userInfoNewVO : userInfo) {
                        commonFloor = userInfoNewVO.getCommonFloor();
                        publicFloor = userInfoNewVO.getPublicFloor();
                    }
                    Map jsonCommonFloor=null;
                    Map jsonPublicFloor=null;
                    if (commonFloor!=null){
                        jsonCommonFloor = JSON.parseObject(commonFloor, HashMap.class);
                    }
                    if (publicFloor!=null){
                        jsonPublicFloor =  JSON.parseObject(publicFloor, HashMap.class);
                    }

                    List<AppFloorDevicesVO> floors = null;
                    if(map.get(padDeviceUnique).equals("1")){
                        floors = iAppDeviceService.getFloorDevices(voUser.getUserId(), appFaceRecognitionDeviceAuthDTO.getProjectId(), 0);
                        for(AppFloorDevicesVO elevator : floors){
                            if(deviceUniqueByElevatorArr.contains(elevator.getDeviceUnique()) && appFaceRecognitionDeviceAuthDTO.getStatus()==2){
                                mark = true;
                                break;
                            }
                        }
                        if(mark){
                            //此处需要重新推送平板有关电梯的最新权限楼层
                            padPullCloudInfoPOAllList = this.elevatorOrderByPad(voUser.getUserId(),padDeviceUnique,appFaceRecognitionDeviceAuthDTO.getProjectId(),padPullCloudInfoPOAllList,floors,commonFloor,publicFloor,jsonCommonFloor,jsonPublicFloor);
                            break;
                        }
                    }else if (map.get(padDeviceUnique).equals("2")){
                        List<AppDoorDevicesVO> doors = iAppDeviceService.getDoorDevices(voUser.getUserId(), appFaceRecognitionDeviceAuthDTO.getProjectId(), 0);
                        for(AppDoorDevicesVO door : doors){
                            if(entranceListByRole.contains(door.getDeviceUnique()) && appFaceRecognitionDeviceAuthDTO.getStatus()==2){
                                mark = true;
                                break;
                            }
                        }
                        if(mark){
                            break;
                        }
                    }
                    PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                    padPullCloudInfoPO.setDeviceUnique(padDeviceUnique);
                    padPullCloudInfoPO.setProjectId(appFaceRecognitionDeviceAuthDTO.getProjectId());
                    voUser.setStatus(appFaceRecognitionDeviceAuthDTO.getStatus() ==2?5:appFaceRecognitionDeviceAuthDTO.getStatus());
                    List<PadFaceUserInfoNewVO> listVo = new ArrayList<>();
                    if (voUser.getUserLabel()==null){
                        voUser.setIsVip(0);
                    }else {
                        voUser.setIsVip(Arrays.asList(voUser.getUserLabel().split(",")).contains("1")?1:0);
                    }
                    listVo.add(voUser);
                    String syncData = JSON.toJSONString(listVo);
                    padPullCloudInfoPO.setSyncData(syncData);
                    padPullCloudInfoPO.setSyncType(2);
                    padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                    padPullCloudInfoPO.setDataType(1);
                    padPullCloudInfoPO.setSyncStatus(1);
                    padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    padPullCloudInfoPO.setCreateTime(nowTime);
                    padPullCloudInfoPO.setUpdateTime(nowTime);
                    //11修改住户角色组信息
                    padPullCloudInfoPO.setInstructionType(11);
                    padPullCloudInfoPO.setSourceSystem(2);
                    iPadFaceSyncDataServiceDao.updatePadOrderByUser(listVo.get(0).getUserId(),padDeviceUnique);//清除当前设备,当前用户之前的1号指令

                    if(appFaceRecognitionDeviceAuthDTO.getStatus()==1){
                        if(map.get(padDeviceUnique).equals("2")) {
                            //处理门禁
                            padPullCloudInfoPOAllList = this.entranceOrderByPad(voUser.getUserId(),padDeviceUnique,appFaceRecognitionDeviceAuthDTO.getProjectId(),padPullCloudInfoPOAllList,commonFloor,publicFloor,jsonCommonFloor,jsonPublicFloor);
                        }else if(map.get(padDeviceUnique).equals("1")){
                            // 电梯
                            padPullCloudInfoPOAllList = this.elevatorOrderByPad(voUser.getUserId(),padDeviceUnique,appFaceRecognitionDeviceAuthDTO.getProjectId(),padPullCloudInfoPOAllList,floors,commonFloor,publicFloor,jsonCommonFloor,jsonPublicFloor);
                        }

                    }
                    padPullCloudInfoPOAllList.add(padPullCloudInfoPO);
                }
            }
        }
        if (padPullCloudInfoPOAllList.size() > 0) {
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOAllList);
            //取得版本和iotkey
            ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOAllList.get(0).getDeviceUnique());
            //将增量数据发送iot到平板设备
            for (PadPullCloudInfoPO po : padPullCloudInfoPOAllList) {
                //过滤离线平板
                if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique())) && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(),"itlong",po.getSyncType().toString(),0,po.getSyncType().toString(),1);
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        }
    }

    /**
     * <desc>
     *      组装推送平板有关门禁指令
     * </desc>
     *
     * @author Juguang.S
     * @createDate 2021/04/22
     */
    public List<PadPullCloudInfoPO> entranceOrderByPad(String userId,String padDeviceUnique,String projectId,List<PadPullCloudInfoPO> padPullCloudInfoPOAllList,
                                                       String commonFloor,String publicFloor,Map jsonCommonFloor,Map jsonPublicFloor){
        //处理门禁
        Date nowTime = new Date();
        List<String> doorList = iPadFaceSyncDataServiceDao.getEntranceListByNotInRoleIdAndUserId("",userId);
        List<String> cloudEntraceList = new ArrayList<>();
        if(doorList!=null && doorList.size()>0){
            //云联动器集合
            cloudEntraceList = iPadFaceSyncDataServiceDao.getEntranceTypeByDeviceUnqiue(doorList);
        }
        Map<String, Object> authDoor = new HashMap<>();
        List<Map<String,Object>> authsDoor = new ArrayList<>();
        List<Map<String, Object>> sysAuthDoor = new ArrayList<>();
        authDoor.put("userId", userId);
        authDoor.put("houseUserType", "5");
        authDoor.put("startTime", "");
        authDoor.put("endTime", "");
        authDoor.put("deviceType", 3);//普通门禁用3
        for (String door : doorList) {
            //查询该设备是否云联动器
            Map<String,Object> sysAuth = new HashMap<>();
            if(cloudEntraceList.contains(door)){
                sysAuth.put("auth","8");
                sysAuth.put("deviceUnique",door);
                if (commonFloor==null){
                    sysAuth.put("commonFloor","");
                }else {
                    StringBuilder builder = new StringBuilder();


                    if (jsonCommonFloor.containsKey(door)){
                        builder.append(jsonCommonFloor.get(door)).append(",");
                    }
                    sysAuth.put("commonFloor",builder.toString().substring(0,builder.length()-1));
                }
                if (publicFloor==null){
                    sysAuth.put("publicFloor","");
                }else {
                    StringBuilder builderp = new StringBuilder();

                    if (jsonPublicFloor.containsKey(door)){
                        builderp.append(jsonPublicFloor.get(door)).append(",");
                    }
                    sysAuth.put("publicFloor",builderp.toString().substring(0,builderp.length()-1));
                }
            }else{
                sysAuth.put("auth", "8");
                sysAuth.put("deviceUnique", door);
            }

            sysAuthDoor.add(sysAuth);
        }
        authDoor.put("sysAuths", sysAuthDoor);
        authsDoor.add(authDoor);

        if (!authsDoor.isEmpty()) {
            PadPullCloudInfoPO padPullCloudInfoPO2 = new PadPullCloudInfoPO();
            padPullCloudInfoPO2.setDeviceUnique(padDeviceUnique);
            padPullCloudInfoPO2.setProjectId(projectId);
            String syncData2 = JSON.toJSONString(authsDoor);
            padPullCloudInfoPO2.setSyncData(syncData2);
            padPullCloudInfoPO2.setSyncType(2);
            padPullCloudInfoPO2.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO2.setDataType(2);
            padPullCloudInfoPO2.setSyncStatus(1);
            padPullCloudInfoPO2.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO2.setCreateTime(nowTime);
            padPullCloudInfoPO2.setUpdateTime(nowTime);
            //11修改住户角色组信息
            padPullCloudInfoPO2.setInstructionType(11);
            padPullCloudInfoPO2.setSourceSystem(2);
            padPullCloudInfoPOAllList.add(padPullCloudInfoPO2);
        }
        return padPullCloudInfoPOAllList;
    }

    /**
     * <desc>
     *      组装推送平板有关电梯指令
     * </desc>
     *
     * @author Juguang.S
     * @createDate 2021/04/22
     */
    public List<PadPullCloudInfoPO> elevatorOrderByPad(String userId,String padDeviceUnique,String projectId,List<PadPullCloudInfoPO> padPullCloudInfoPOAllList,List<AppFloorDevicesVO> floors,
                                                       String commonFloor,String publicFloor,Map jsonCommonFloor,Map jsonPublicFloor){
        //处理电梯
        Date nowTime = new Date();
        List<Map<String,Object>> authsElevator = new ArrayList<>();
        if (floors != null && !floors.isEmpty()) {
            Map<String, Object> authElevator = new HashMap<>();
            List<Map<String,Object>> sysAuthElevator = new ArrayList<>();
            authElevator.put("userId",userId);
            authElevator.put("houseUserType","5");
            authElevator.put("startTime","");
            authElevator.put("endTime","");
            authElevator.put("deviceType",2);
            for (AppFloorDevicesVO floor : floors) {
                Map<String,Object> sysAuth = new HashMap<>();
                sysAuth.put("auth",floor.getLiveFloor());
                sysAuth.put("deviceUnique",floor.getDeviceUnique());
                if (commonFloor==null){
                    sysAuth.put("commonFloor","");
                }else {
                    StringBuilder builder = new StringBuilder();


                    if (jsonCommonFloor.containsKey(floor)){
                        builder.append(jsonCommonFloor.get(floor)).append(",");
                    }
                    sysAuth.put("commonFloor",("".equals(builder+""))?"":(builder.toString().substring(0,(builder.length()-1))));

                }
                if (publicFloor==null){
                    sysAuth.put("publicFloor","");
                }else {
                    StringBuilder builderp = new StringBuilder();

                    if (jsonPublicFloor.containsKey(floor)){
                        builderp.append(jsonPublicFloor.get(floor)).append(",");
                    }
                    sysAuth.put("publicFloor",("".equals(builderp+""))?"":builderp.toString().substring(0,builderp.length()-1));

                }
                sysAuthElevator.add(sysAuth);
            }
            authElevator.put("sysAuths",sysAuthElevator);
            authsElevator.add(authElevator);
        }
        if (!authsElevator.isEmpty()) {
            PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
            padPullCloudInfoPO3.setDeviceUnique(padDeviceUnique);
            padPullCloudInfoPO3.setProjectId(projectId);
            String syncData3 = JSON.toJSONString(authsElevator);
            padPullCloudInfoPO3.setSyncData(syncData3);
            padPullCloudInfoPO3.setSyncType(2);
            padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO3.setDataType(2);
            padPullCloudInfoPO3.setSyncStatus(1);
            padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO3.setCreateTime(nowTime);
            padPullCloudInfoPO3.setUpdateTime(nowTime);
            //10:住户角色组信息人员分配
            padPullCloudInfoPO3.setInstructionType(10);
            //2物业后台
            padPullCloudInfoPO3.setSourceSystem(2);
            padPullCloudInfoPOAllList.add(padPullCloudInfoPO3);
        }
        return padPullCloudInfoPOAllList;
    }

    /**
     * <desc>
     *      推送用户权限信息变更消息
     * </desc>
     *
     * @param auths
     * @author Jiaqi.X
     * @createDate 2019/01/24
     */
    @Override
    public void pushUserAuthChange(String userId, String roomId, List<Map<String,Object>> auths, String projectId,Integer InstructionType,Integer sourceSystem) throws Exception {
        List<String> deviceUniques = iPadFaceSyncDataServiceDao.getPadDeviceUniquesByRoomId(roomId);
        List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
        for (String deviceUnique : deviceUniques) {
            List<Map<String,Object>> nAuths = this.deepCopy(auths);
            //推送用户人脸状态信息
            //获取平板的地址
            List<Map<String, Object>> builds = iPadFaceSyncDataServiceDao.getAddressByDeviceUnique(deviceUnique);
            List<PadFaceUserInfoVO> vos = null;
            if (builds.size() > 1) {
                //多楼栋
                List<String> bs = new ArrayList<>();
                builds.forEach(build -> {
                    bs.add(build.get("buildId").toString());
                });
                vos = iPadFaceSyncDataServiceDao.getUserInfosByBuildsAndUserId(bs, StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique), userId);
                vos.forEach(vo -> {
                    if (vo.getStatus() == PadUserStatusEnum.NORMAL.getType() && vo.getOutstandingAccounts() > 0) {
                        vo.setStatus(2);
                    }
                    if (vo.getUserLabel()==null){
                        vo.setIsVip(0);
                    }else {
                        vo.setIsVip(Arrays.asList(vo.getUserLabel().split(",")).contains("1")?1:0);
                    }

                });
                if (vos.size() == 0) {
                    PadFaceUserInfoVO vo = new PadFaceUserInfoVO();
                    vo.setUserId(userId);
                    vo.setImageUrl("");
                    vo.setStatus(5);
                    vo.setOutstandingAccounts(1);
                    vo.setUserName("");
                    vo.setHouseUserType("5");
                    vo.setStartTime("");
                    vo.setEndTime("");
                    vo.setIsVip(0);
                    vos.add(vo);
                }
            } else if (builds.size() == 1) {
                //多单元
                String[] unit = StringHandlerUtil.splitString(builds.get(0).get("unitId").toString());
                vos = iPadFaceSyncDataServiceDao.getUserInfosByUnitsAndUserId(unit, StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique), userId);
                vos.forEach(vo -> {
                    if (vo.getStatus() == PadUserStatusEnum.NORMAL.getType() && vo.getOutstandingAccounts() > 0) {
                        vo.setStatus(2);
                    }
                    if (vo.getUserLabel()==null){
                        vo.setIsVip(0);
                    }else {
                        vo.setIsVip(Arrays.asList(vo.getUserLabel().split(",")).contains("1")?1:0);
                    }
                });
                if (vos.size() == 0) {
                    PadFaceUserInfoVO vo = new PadFaceUserInfoVO();
                    vo.setUserId(userId);
                    vo.setImageUrl("");
                    vo.setStatus(5);
                    vo.setOutstandingAccounts(1);
                    vo.setUserName("");
                    vo.setHouseUserType("5");
                    vo.setStartTime("");
                    vo.setEndTime("");
                    vo.setIsVip(0);
                    vos.add(vo);
                }
            }

            //推送权限信息
            //在推送设备权限指令时判断人脸识别设备是否绑定了群控器
            List<PropertyDeviceCloudControllerEleVO> cloudElevatorList = new ArrayList<>();
            List<String> padDeviceUniqueList = new ArrayList<>();
            padDeviceUniqueList.add(deviceUnique);
            List<Map<String, Object>> deviceUniqueMapList = iPropertyPadDao.getBindDeviceUniqueByPad(padDeviceUniqueList);//绑定设备编号逗号分隔
            if (deviceUniqueMapList.size() > 0 && deviceUniqueMapList.get(0).get("bindDeviceUnique") != null
                    && StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUniqueMapList.get(0).get("bindDeviceUnique").toString().substring(0,13)) == 5) {//只有一条此刻,判断是否绑定了群控器
                String[] bindDeviceUniqueS = deviceUniqueMapList.get(0).get("bindDeviceUnique").toString().split(",");//绑定设备
                for (String bindDeviceUnique : bindDeviceUniqueS) {
                    //根据群控器查询出对应云电梯
                    PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO = new PropertyDeviceCloudControllerGetDTO();
                    propertyDeviceCloudControllerGetDTO.setProjectId(projectId);
                    propertyDeviceCloudControllerGetDTO.setDeviceId(bindDeviceUnique.substring(bindDeviceUnique.length() - 4, bindDeviceUnique.length()));
                    PropertyDeviceCloudControllerGetVO vo = iDeviceCloudControllerService.getOne(propertyDeviceCloudControllerGetDTO);
                    for (PropertyDeviceCloudControllerEleVO controller : vo.getCloudElevatorList()) {//将群控器编号放回list中
                        controller.setDeviceUniqueContrroller(vo.getDeviceUnique());
                    }
                    //拼接所有云电梯
                    cloudElevatorList.addAll(vo.getCloudElevatorList());
                }
                //判断云电梯是否为绑定群控器控制,并替换云电梯的设备编号为群控器编号
                for (Map<String,Object> mapUser : nAuths) {
                    List<Map<String,Object>> sysAuths = (List<Map<String,Object>>) mapUser.get("sysAuths");
                    //存电梯对象的新容器
                    Map<String,Object> sMap = new HashMap<>();
                    //替换原sysAuths的新容器
                    List<Map<String,Object>> newSysAuths = new ArrayList<>();
                    //判断已遍历过的电梯对应群控机号是否已处理过
                    Set<String> deviceUniqueSet = new HashSet<>();
                    for (Map<String,Object> mapAuth : sysAuths) {//循环权限
                        //找出当前sysAuth对应的控制器信息
                        Optional<PropertyDeviceCloudControllerEleVO> optional = cloudElevatorList.stream().filter(vo -> vo.getDeviceUniqueElevator().equals(mapAuth.get("deviceUnique").toString())).findFirst();
                        PropertyDeviceCloudControllerEleVO controllerVo = optional.isPresent() ? optional.get() : null;
                        if (controllerVo != null) {//有当前群控器管控的云电梯时
                            if (deviceUniqueSet.add(controllerVo.getDeviceUniqueContrroller())) {
                                //第一次处理
                                mapAuth.put("deviceUnique", controllerVo.getDeviceUniqueContrroller());
                                sMap.put(controllerVo.getDeviceUniqueContrroller(), mapAuth);
                            } else {
                                Map<String, Object> repeatMap = (HashMap) sMap.get(controllerVo.getDeviceUniqueContrroller());
                                //替换操作 mapAuth  / repeatMap
                                String auth = StringHandlerUtil.duplicateEemoval(mapAuth.get("auth").toString() + "," + repeatMap.get("auth"));
                                repeatMap.put("auth", auth);
                            }
                        } else {//没有管控的直接无条件添加
                            newSysAuths.add(mapAuth);
                            continue;
                        }
                    }
                    for(String key : sMap.keySet()){
                        newSysAuths.add((HashMap)sMap.get(key));
                    }
                    mapUser.put("sysAuths", newSysAuths);
                }
            }

            PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
            padPullCloudInfoPO.setDeviceUnique(deviceUnique);
            padPullCloudInfoPO.setProjectId(projectId);
            padPullCloudInfoPO.setSyncData(JsonUtil.toJSON(nAuths));
            padPullCloudInfoPO.setSyncType(2);
            padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO.setDataType(2);
            padPullCloudInfoPO.setSyncStatus(1);
            padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO.setCreateTime(new Date());

            padPullCloudInfoPO.setInstructionType(InstructionType);
            padPullCloudInfoPO.setSourceSystem(sourceSystem);

            padPullCloudInfoPOList.add(padPullCloudInfoPO);
            for (PadFaceUserInfoVO vo : vos) {
                List<PadFaceUserInfoVO> voList = new ArrayList<>();
                //组装vip
                if (vo.getUserLabel()==null){
                    vo.setIsVip(0);
                }else {
                    vo.setIsVip(Arrays.asList(vo.getUserLabel().split(",")).contains("1")?1:0);
                }

                voList.add(vo);
                //推送用户信息
                PadPullCloudInfoPO padPullCloudInfoUser = new PadPullCloudInfoPO();
                padPullCloudInfoUser.setDeviceUnique(deviceUnique);
                padPullCloudInfoUser.setProjectId(projectId);
                padPullCloudInfoUser.setSyncData(JsonUtil.toJSON(voList));
                padPullCloudInfoUser.setSyncType(2);
                padPullCloudInfoUser.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoUser.setDataType(1);
                padPullCloudInfoUser.setSyncStatus(1);
                padPullCloudInfoUser.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoUser.setCreateTime(new Date());
                iPadFaceSyncDataServiceDao.updatePadOrderByUser(voList.get(0).getUserId(),deviceUnique);//清除当前设备,当前用户之前的1号指令
                padPullCloudInfoPOList.add(padPullCloudInfoUser);
            }
        }
        if (padPullCloudInfoPOList.size() > 0) {
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
            //取得版本和iotkey
            ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOList.get(0).getDeviceUnique());
            //将增量数据发送iot到平板设备
            for (PadPullCloudInfoPO po : padPullCloudInfoPOList) {
                //过滤离线平板
                if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))
                        && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(), "itlong", po.getSyncType().toString(), 0, po.getSyncType().toString(), 1);
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        }
    }

    /**
     * <desc>
     *     推送全量数据
     * </desc>
     *
     * @param deviceUnique
     * @param projectId
     * @author Jiaqi.X
     * @createDate 2019/01/24
     */
    @Override
    public void pushFull(String deviceUnique, String projectId) {
        PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
        padPullCloudInfoPO.setDeviceUnique(deviceUnique);
        padPullCloudInfoPO.setProjectId(projectId);
        padPullCloudInfoPO.setSyncData("");
        padPullCloudInfoPO.setSyncType(1);
        padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
        padPullCloudInfoPO.setDataType(4);
        padPullCloudInfoPO.setSyncStatus(1);
        padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
        padPullCloudInfoPO.setCreateTime(new Date());
        List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
        padPullCloudInfoPOList.add(padPullCloudInfoPO);
        iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        //取得版本和iotkey
        ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOList.get(0).getDeviceUnique());
        //将增量数据发送iot到平板设备
        for (PadPullCloudInfoPO po : padPullCloudInfoPOList) {
            //过滤离线平板
            if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))
                    && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                        "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                        po.getDeviceUnique(),"itlong",po.getSyncType().toString(),0,po.getSyncType().toString(),1);
                sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
            }
        }
    }

    /**
     * <desc>
     *      增量获取变更数据
     * </desc>
     *
     * @param projectId 项目编号
     * @return 增量数据
     * @author wangzhi
     * @createDate 2019/03/18
     */
    @Override
    public List<SmartCardIncrementUpdateGetVO> getIncrementUpdateSmartCard(String projectId) throws Exception {
        List<SmartCardIncrementUpdateGetVO> smartCardIncrementUpdateGetVOS = iPadFaceSyncDataServiceDao.getIncrementUpdateSmartCard(projectId);
        if (smartCardIncrementUpdateGetVOS != null && !smartCardIncrementUpdateGetVOS.isEmpty()) {
            List<String> syncSerialNos = new ArrayList<>();
            for (SmartCardIncrementUpdateGetVO smartCardIncrementUpdateGetVO : smartCardIncrementUpdateGetVOS){
                syncSerialNos.add(smartCardIncrementUpdateGetVO.getSyncSerialNo());
            }
            // 同步状态设置为同步中
            Map<String, Object> map = new HashMap<>();
            map.put("syncSerialNos",syncSerialNos);
            map.put("syncStatus",2); // 同步状态标志 1.待同步；2.同步中;3.同步结束
            iPadFaceSyncDataServiceDao.setSyncStatusSmartCard(map);
        }
        return smartCardIncrementUpdateGetVOS;
    }

    /**
     * <desc>
     *      修改同步状态为同步结束
     * </desc>
     *
     * @param syncSerialNo 同步流水号，多个用英文逗号相连
     * @return 0-失败 1-成功
     * @author wangzhi
     * @createDate 2019/03/18
     */
    @Override
    public Integer updateSyncStatusSmartCard(String syncSerialNo) throws Exception {
        List<String> syncSerialNos = StringHandlerUtil.splitStringList(syncSerialNo);
        // 同步状态设置为同步结束
        Map<String, Object> map = new HashMap<>();
        map.put("syncSerialNos",syncSerialNos);
        map.put("syncStatus",3); // 同步状态标志 1.待同步；2.同步中;3.同步结束
        return iPadFaceSyncDataServiceDao.setSyncStatusSmartCard(map);
    }


    /**
     * <desc>
     *      获取访客单元下的电梯及对应电梯的楼层权限
     * </desc>
     *
     * @param unitId
     * @param floorNum
     * @return
     * @author Jiaqi.X
     * @createDate 2019/06/06
     *
     */
    @Override
    public List<Map<String,Object>> getElevatorsByUnitId(String unitId,String floorNum){
        return iPadFaceSyncDataServiceDao.getElevatorsByUnitId(unitId,floorNum);
    }

    /**
     * <desc>
     *      拷贝list数据
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2020/01/16
     *
     */
    public <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);

        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        @SuppressWarnings("unchecked")
        List<T> dest = (List<T>) in.readObject();
        return dest;
    }

    /**
     * <desc>
     *      查询用户是否有人脸
     * </desc>
     *
     * @param userId 用户编号
     * @param projectId 项目编号
     * @return
     * @author Juguang.S
     * @createDate 2020/05/20
     */
    @Override
    public String getFacePicUrl(String userId, String projectId){
        return iPadFaceSyncDataServiceDao.getFacePicUrl(userId, projectId);
    }

    /**
     * <desc>
     *      sdk注销用户时处理平板用户指令
     * </desc>
     *
     * @param userId 用户编号
     * @return
     * @author Qiang.S
     * @createDate 2020/07/03
     */
    @Override
    public void userSyncForSDK(String userId){
        List<String> projects = iPadFaceSyncDataServiceDao.getUserPorject(userId);
        for (String projectId : projects) {
            List<String> buildIds = iPadFaceSyncDataServiceDao.getBuildIdsOfUser(userId,projectId);
            List<String>   deviceUniques = iPadFaceSyncDataServiceDao.getPadDeviceUniques(buildIds);
            List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
            Date nowTime = new Date();
            for (String deviceUnique : deviceUniques){
                PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
                padFaceSyncDataUserVO.setUserName("");
                padFaceSyncDataUserVO.setUserId(userId);
                padFaceSyncDataUserVO.setImageUrl("");
                padFaceSyncDataUserVO.setStatus("5");//删除
                padFaceSyncDataUserVO.setOutstandingAccounts("");
                padFaceSyncDataUserVO.setHouseUserType("5");
                padFaceSyncDataUserVO.setStartTime("");
                padFaceSyncDataUserVO.setEndTime("");
                List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                list.add(padFaceSyncDataUserVO);
                String syncData = JSON.toJSONString(list);
                PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                padPullCloudInfoPO.setDeviceUnique(deviceUnique);
                padPullCloudInfoPO.setProjectId(projectId);
                padPullCloudInfoPO.setSyncData(syncData);
                padPullCloudInfoPO.setSyncType(2);
                padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO.setDataType(1);
                padPullCloudInfoPO.setSyncStatus(1);
                padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO.setCreateTime(nowTime);
                padPullCloudInfoPO.setUpdateTime(nowTime);
                padPullCloudInfoPOList.add(padPullCloudInfoPO);
            }
            if (padPullCloudInfoPOList.size() > 0) {
                iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
                //取得版本和iotkey
                ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOList.get(0).getDeviceUnique());
                //将增量数据发送iot到平板设备
                for (PadPullCloudInfoPO po : padPullCloudInfoPOList) {
                    //过滤离线平板
                    if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))
                            && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                        SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                                "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                                po.getDeviceUnique(), "itlong", po.getSyncType().toString(), 0, po.getSyncType().toString(), 1);
                        sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                    }
                }
            }
        }
    }

    /**
     * <desc>
     *      京东 sdk注销用户时处理平板用户指令
     * </desc>
     *
     * @param userId 用户编号
     * @return
     * @Author Zhu.yj
     * @createDate  2020/12/18
     */
    @Override
    public void jdUserSyncForSDK(String userId, String projectId) {
        if (StringUtils.isBlank(projectId) ){
            return;
        }
        List<PadFaceSyncDataUserVO> visitorList = iPadFaceSyncDataServiceDao.getVisitorListByUserId(userId, projectId);
        List<String> deviceUniques = this.getPadDeviceUniqueList(userId, projectId);
        List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
        Date nowTime = new Date();
        for (String deviceUnique : deviceUniques) {
            PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
            List<PadFaceSyncDataUserVO> list = new ArrayList<>();
            //用户注销
            padFaceSyncDataUserVO.setUserName("");
            padFaceSyncDataUserVO.setUserId(userId);
            padFaceSyncDataUserVO.setImageUrl("");
            padFaceSyncDataUserVO.setStatus("5");//删除
            padFaceSyncDataUserVO.setOutstandingAccounts("");
            padFaceSyncDataUserVO.setHouseUserType("5");
            padFaceSyncDataUserVO.setStartTime("");
            padFaceSyncDataUserVO.setEndTime("");
            list.add(padFaceSyncDataUserVO);
            String syncData = JSON.toJSONString(list);
            PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
            padPullCloudInfoPO.setDeviceUnique(deviceUnique);
            padPullCloudInfoPO.setProjectId(projectId);
            padPullCloudInfoPO.setSyncData(syncData);
            padPullCloudInfoPO.setSyncType(2);
            padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO.setDataType(1);
            padPullCloudInfoPO.setSyncStatus(1);
            padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO.setCreateTime(nowTime);
            padPullCloudInfoPO.setUpdateTime(nowTime);
            padPullCloudInfoPOList.add(padPullCloudInfoPO);

            //因人脸识别仪接收syncData是用list接收，但只get(0)，所以当有多个访客时发多条
            for (PadFaceSyncDataUserVO padFaceSyncDataUserVO1 : visitorList){
                List<PadFaceSyncDataUserVO> padFaceSyncDataUserVOS = new ArrayList<>();
                padFaceSyncDataUserVOS.add(padFaceSyncDataUserVO1);
                String syncData1 = JSON.toJSONString(padFaceSyncDataUserVOS);
                PadPullCloudInfoPO padPullCloudInfoPO1 = new PadPullCloudInfoPO();
                padPullCloudInfoPO1.setDeviceUnique(deviceUnique);
                padPullCloudInfoPO1.setProjectId(projectId);
                padPullCloudInfoPO1.setSyncData(syncData1);
                padPullCloudInfoPO1.setSyncType(2);
                padPullCloudInfoPO1.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO1.setDataType(1);
                padPullCloudInfoPO1.setSyncStatus(1);
                padPullCloudInfoPO1.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO1.setCreateTime(nowTime);
                padPullCloudInfoPO1.setUpdateTime(nowTime);
                padPullCloudInfoPOList.add(padPullCloudInfoPO1);
            }

        }
        if (padPullCloudInfoPOList.size() > 0) {
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
            //取得版本和iotkey
            ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOList.get(0).getDeviceUnique());
            //将增量数据发送iot到平板设备
            for (PadPullCloudInfoPO po : padPullCloudInfoPOList) {
                //过滤离线平板
                if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))
                        && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(), "itlong", po.getSyncType().toString(), 0, po.getSyncType().toString(), 1);
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        }
    }

    /**
     * <desc>
     *      注销用户时处理平板用户指令
     * </desc>
     *
     * @param userId 用户编号
     * @return
     * @Author Juguang.S
     * @createDate  2021/05/21
     */
    @Override
    public void userSyncForFaceUrl(String userId, String projectId) throws Exception{
        if (StringUtils.isBlank(projectId) ){
            return;
        }
        List<PadFaceSyncDataUserVO> visitorList = iPadFaceSyncDataServiceDao.getVisitorListByUserId(userId, projectId);
        List<String> deviceUniques = this.getPadDeviceUniqueList(userId, projectId);
        //查询用户有关联门禁所绑平板的设备机号

        List<String> elevatorDeviceUniqueList = new ArrayList<>();
        List<String> deviceUniquesByEntrance = new ArrayList<>();
        List<String> entrance = new ArrayList<>();
        List<AppDoorDevicesVO> doors = iAppDeviceService.getDoorDevices(userId, projectId, 1);
        if(doors!=null && doors.size()>0){
            for(AppDoorDevicesVO doorDevicesVO : doors){
                entrance.add(doorDevicesVO.getDeviceUnique());
            }
        }
        if (!entrance.isEmpty()){
            //根据电梯deviceUnique找出绑定该电梯的平板deviceUnique列表
            deviceUniquesByEntrance = iPadFaceSyncDataServiceDao.getBindElevatorPadList(entrance);
        }
        if(deviceUniquesByEntrance!=null && deviceUniquesByEntrance.size()>0 && deviceUniques!=null && deviceUniques.size()>0){
            deviceUniques.addAll(deviceUniquesByEntrance);
        }else if(deviceUniques==null && deviceUniquesByEntrance!=null && deviceUniquesByEntrance.size()>0){
            deviceUniques=deviceUniquesByEntrance;
        }

        List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
        Date nowTime = new Date();
        for (String deviceUnique : deviceUniques) {
            PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
            List<PadFaceSyncDataUserVO> list = new ArrayList<>();
            //用户注销
            padFaceSyncDataUserVO.setUserName("");
            padFaceSyncDataUserVO.setUserId(userId);
            padFaceSyncDataUserVO.setImageUrl("");
            padFaceSyncDataUserVO.setStatus("5");//删除
            padFaceSyncDataUserVO.setOutstandingAccounts("");
            padFaceSyncDataUserVO.setHouseUserType("5");
            padFaceSyncDataUserVO.setStartTime("");
            padFaceSyncDataUserVO.setEndTime("");
            list.add(padFaceSyncDataUserVO);
            String syncData = JSON.toJSONString(list);
            PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
            padPullCloudInfoPO.setDeviceUnique(deviceUnique);
            padPullCloudInfoPO.setProjectId(projectId);
            padPullCloudInfoPO.setSyncData(syncData);
            padPullCloudInfoPO.setSyncType(2);
            padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO.setDataType(1);
            padPullCloudInfoPO.setSyncStatus(1);
            padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO.setCreateTime(nowTime);
            padPullCloudInfoPO.setUpdateTime(nowTime);
            padPullCloudInfoPOList.add(padPullCloudInfoPO);

            //因人脸识别仪接收syncData是用list接收，但只get(0)，所以当有多个访客时发多条
            for (PadFaceSyncDataUserVO padFaceSyncDataUserVO1 : visitorList){
                List<PadFaceSyncDataUserVO> padFaceSyncDataUserVOS = new ArrayList<>();
                padFaceSyncDataUserVOS.add(padFaceSyncDataUserVO1);
                String syncData1 = JSON.toJSONString(padFaceSyncDataUserVOS);
                PadPullCloudInfoPO padPullCloudInfoPO1 = new PadPullCloudInfoPO();
                padPullCloudInfoPO1.setDeviceUnique(deviceUnique);
                padPullCloudInfoPO1.setProjectId(projectId);
                padPullCloudInfoPO1.setSyncData(syncData1);
                padPullCloudInfoPO1.setSyncType(2);
                padPullCloudInfoPO1.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO1.setDataType(1);
                padPullCloudInfoPO1.setSyncStatus(1);
                padPullCloudInfoPO1.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO1.setCreateTime(nowTime);
                padPullCloudInfoPO1.setUpdateTime(nowTime);
                padPullCloudInfoPOList.add(padPullCloudInfoPO1);
            }

        }
        if (padPullCloudInfoPOList.size() > 0) {
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
            //取得版本和iotkey
            ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOList.get(0).getDeviceUnique());
            //将增量数据发送iot到平板设备
            for (PadPullCloudInfoPO po : padPullCloudInfoPOList) {
                //过滤离线平板
                if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))
                        && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                    SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                            "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                            po.getDeviceUnique(), "itlong", po.getSyncType().toString(), 0, po.getSyncType().toString(), 1);
                    sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
                }
            }
        }
    }

    /**
     * <desc>
     *      京东住户信息变更及住户权限变更触发平板人脸识别离线优先同步数据
     * </desc>
     *
     * @param padFaceSyncDataDTO 平板人脸增量同步数据DTO
     * @return 0失败，1成功
     * @author Zhu.yj
     * @createDate 2020/12/9
     */
    @Override
    public Integer jdUserDataSync(PadFaceSyncDataDTO padFaceSyncDataDTO) throws Exception {
        importAddressFixedThreadPool.execute(() -> {
            try {
                int i = jdUserDataSyncExecute(padFaceSyncDataDTO);
                if (i == 1) {
                    //LOG.info("【住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据执行成功】" + padFaceSyncDataDTO);
                } else {
                    LOG.info("【住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据执行失败，但无异常】" + padFaceSyncDataDTO);
                }
            } catch (Exception e) {
                LOG.error("【住户信息变更和楼层映射信息变更触发平板人脸识别离线优先同步数据执行失败】" + padFaceSyncDataDTO, e);
            }
        });
        return 1;
    }

    /**
     * <desc>
     *      异步修改人脸照片,京东设置超时时间为5s，
     * </desc>
     *
     * @param padFaceSyncDataDTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/1/27
     */
    public void   jdUpdatePhotoSync(PadFaceSyncDataDTO padFaceSyncDataDTO){
        importAddressFixedThreadPool.execute(() -> {
            try {
                byte[] bytes = VerifyCodeUtils.getFileStream(padFaceSyncDataDTO.getPhotoUrl(), "");
                String uploadFilePath = uploadImageFile(bytes, "png", FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
                Map<String, Object> params = new HashMap<>();
                params.put("updateTime", new Date());
                params.put("facePicUrl", uploadFilePath);
                params.put("projectId", padFaceSyncDataDTO.getProjectId());
                params.put("userId", padFaceSyncDataDTO.getAppUserIds());
                iPadFaceSyncDataServiceDao.updateUserFace(params);
                iPadFaceSyncDataServiceDao.updateVisitorFace(params);
            }catch (Exception e){
                LOG.info("修改人脸失败");
                throw new DataAccessException("【异步修改人脸照片失败】", e);
            }
        });
    }

    /**
     * <desc>
     *      无地址平板上电获取全量数据
     * </desc>
     *
     * @param bandDeviceUnique 绑定设备类表
     * @param deviceUnique 平板设备唯一码
     * @param type 设备类型
     * @return
     * @author Jiaqi.X
     * @createDate 2019/01/23
     */
    @Override
    public Map<String, Object> pullFullNoAddress(String bandDeviceUnique, String deviceUnique, Integer type) throws Exception{
        //获取有该平板权限的用户，通过找拥有bandDeviceUnique权限的用户
        List<String> userIdList = new ArrayList<>();
        Map<String,Object> data = new HashMap<>();
        String projectId = StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique);
        List<Map<String, Object>>  userElevatorList = iPadFaceSyncDataServiceDao.getAllElevatorAuthByProjectId(projectId);
        //找出有该权限的访客列表
        for (Map<String, Object> userElevatorMap : userElevatorList){
            List<String> deviceIds = StringHandlerUtil.splitStringList(StringHandlerUtil.convertAuth(userElevatorMap.get("deviceAuth").toString(), "1"));
            for (String deviceId : deviceIds){
                String elevatorDeviceUnique = StringHandlerUtil.getDeviceUniqueId(projectId, 1, deviceId);
                if (bandDeviceUnique.contains(elevatorDeviceUnique)){
                    userIdList.add(userElevatorMap.get("userId").toString());
                }
            }
        }
        if (!userIdList.isEmpty()){
            List<PadFaceUserInfoVO> userInfoVOS = iPadFaceSyncDataServiceDao.getPadUserInfo(userIdList);
            List<PadFaceUserInfoVO>  visitorInfoVOs = iPadFaceSyncDataServiceDao.getPadVisitorInfo(userIdList);
            userInfoVOS.addAll(visitorInfoVOs);
            data.put("userInfos", userInfoVOS);
        }
        if(type == 1) {
            List<Map<String,Object>> floors = new ArrayList<>();
            for (String strBandDeviceUnique : bandDeviceUnique.split(",")) {
                //获取电梯起始楼层及结束楼层
                Map<String,Object> minAndMaxFloor = iPadFaceSyncDataServiceDao.getMinAndMaxFloor(strBandDeviceUnique);
                Integer startFloor = minAndMaxFloor==null || minAndMaxFloor.get("minFloor") == null ? null : Double.valueOf(minAndMaxFloor.get("minFloor").toString()).intValue();
                Integer endFloor = minAndMaxFloor==null || minAndMaxFloor.get("maxFloor") == null ? null : Double.valueOf(minAndMaxFloor.get("maxFloor").toString()).intValue();
                Map<String,Object> floor = new HashMap<>();
                floor.put("floorMapping",iPadFaceSyncDataServiceDao.getFloorsByDeviceUnique(strBandDeviceUnique,startFloor,endFloor));
                floor.put("deviceUnique",strBandDeviceUnique);
                floors.add(floor);
            }
            data.put("floors", floors);
        }
        iPadFaceSyncDataServiceDao.deletePullDataByDeviceUnique(deviceUnique);
        return data;
    }

    /**
     * <desc>
     *      京东住户信息变更及住户权限变更触发平板人脸识别离线优先同步数据
     * </desc>
     *
     * @param padFaceSyncDataDTO 平板人脸增量同步数据DTO
     * @return 0失败，1成功
     * @author Zhu.yj
     * @createDate 2020/12/9
     */
    private Integer jdUserDataSyncExecute(PadFaceSyncDataDTO padFaceSyncDataDTO) throws Exception{
        // 人脸注册那边是异步，这边5秒后再开始
        Thread.sleep(5000);
        Date nowTime = new Date();
        List<PadPullCloudInfoPO> padPullCloudInfoPOList = new ArrayList<>();
        switch (PadOperateTypeEnum.getByType(padFaceSyncDataDTO.getOperateType())){
            case USER_INFO_MODIFY:
                this.userInfoSync(padFaceSyncDataDTO, padPullCloudInfoPOList, nowTime);
                break;
            case FACE_REGISTER:
                this.faceRegister(padFaceSyncDataDTO, padPullCloudInfoPOList, nowTime);
                break;
            case VISITOR_FACE_REGISTER:
                this.visitorFaceRegister(padFaceSyncDataDTO, padPullCloudInfoPOList, nowTime);
                break;
                default:
                    return 1;
        }
        //取得版本和iotkey
        ProductTypePO productKey = iPadFaceSyncDataServiceDao.getPadVersonIotkey(padPullCloudInfoPOList.get(0).getDeviceUnique());
        //将增量数据发送iot到平板设备
        for (PadPullCloudInfoPO po : padPullCloudInfoPOList) {
            //过滤离线平板
            if (!StringUtils.isBlank(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique())) && "2".equals(redisService.get(RedisConstant.DEVICE_PAD_IS_ONLINE_KEY + po.getDeviceUnique()))) {
                SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                        "/" + po.getDeviceUnique() + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                        po.getDeviceUnique(),"itlong",po.getSyncType().toString(),0,po.getSyncType().toString(),1);
                sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);
            }
        }
        return 1;
    }

    /**
     * <desc>
     *      京东 用户信息变更推送平板指令
     * </desc>
     *
     * @param padFaceSyncDataDTO 平板人脸增量同步数据DTO
     * @return 0失败，1成功
     * @Author Zhu.yj
     * @createDate  2020/12/9
     */
    private void userInfoSync(PadFaceSyncDataDTO padFaceSyncDataDTO, List<PadPullCloudInfoPO> padPullCloudInfoPOList, Date nowTime) throws Exception{

        if (StringUtils.isBlank(padFaceSyncDataDTO.getAppUserIds())){
            return;
        }
        List<Map<String, Object>> SyncDataListMap = new ArrayList<>();
        String facePicUrl = iPadFaceSyncDataServiceDao.getFacePicUrl(padFaceSyncDataDTO.getAppUserIds(),padFaceSyncDataDTO.getProjectId());
        if (StringUtils.isBlank(facePicUrl)) {
            return;
        }
        String username = iPadFaceSyncDataServiceDao.getUsername(padFaceSyncDataDTO.getAppUserIds());
        List<String> deviceUniques = this.getPadDeviceUniqueList(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId());

        if (deviceUniques == null || deviceUniques.isEmpty()) {
            return;
        }
        for (String deviceUnique : deviceUniques){
            Map<String, Object> map = new HashMap<>();
            map.put("deviceUnique", deviceUnique);
            map.put("username", username == null ? "" : username);
            map.put("userId", padFaceSyncDataDTO.getAppUserIds());
            map.put("imageUrl", facePicUrl);
            // 用户禁用启用状态 1正常 5禁用 4冻结 2欠费
            if (StringUtils.isNotBlank(padFaceSyncDataDTO.getStatus())) {
                map.put("status", padFaceSyncDataDTO.getStatus());
            } else {
                // 先判断用户项目冻结状态
                map.put("status", "1".equals(iPadFaceSyncDataServiceDao.getUserProjectStatus(padFaceSyncDataDTO.getAppUserIds(),padFaceSyncDataDTO.getProjectId())) ? "1" : "4");
                // 用户未冻结，则判断用户禁用状态
                if ("1".equals(map.get("status"))) {
                    map.put("status","1".equals(iPadFaceSyncDataServiceDao.getUserStatus(padFaceSyncDataDTO.getAppUserIds())) ? "1" : "5");
                }
            }
            // 用户是否欠物业费用 0是 1否 2019/02/14 下午与有为沟通后，废弃此字段，合在上面status字段中
            map.put("outstandingAccounts", "1");
            Integer accountByRoomId = null;
            SyncDataListMap.add(map);
        }
        if (SyncDataListMap.isEmpty()) {
            return;
        }
        Map<String,List<PadFaceSyncDataUserVO>> SyncDataMapList = new HashMap<>();
        for (Map map : SyncDataListMap){
            PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
            padFaceSyncDataUserVO.setUserName(map.get("username").toString());
            padFaceSyncDataUserVO.setUserId(map.get("userId").toString());
            padFaceSyncDataUserVO.setImageUrl(map.get("imageUrl").toString());
            padFaceSyncDataUserVO.setStatus(map.get("status").toString());
            padFaceSyncDataUserVO.setOutstandingAccounts(map.get("outstandingAccounts").toString());
            padFaceSyncDataUserVO.setHouseUserType("5");
            padFaceSyncDataUserVO.setStartTime("");
            padFaceSyncDataUserVO.setEndTime("");
            String deviceUnique = map.get("deviceUnique").toString();
            if (SyncDataMapList.get(deviceUnique) == null) {
                List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                list.add(padFaceSyncDataUserVO);
                SyncDataMapList.put(deviceUnique,list);
            } else {
                SyncDataMapList.get(deviceUnique).add(padFaceSyncDataUserVO);
            }
        }
        if (SyncDataMapList.isEmpty()) {
            return;
        }
        // 组装插入表的数据
        SyncDataMapList.forEach((key, value) -> {
            for (PadFaceSyncDataUserVO vo : value) {
                List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                list.add(vo);
                PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                padPullCloudInfoPO.setDeviceUnique(key);
                padPullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData = JSON.toJSONString(list);
                padPullCloudInfoPO.setSyncData(syncData);
                padPullCloudInfoPO.setSyncType(2);
                padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO.setDataType(1);
                padPullCloudInfoPO.setSyncStatus(1);
                padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO.setCreateTime(nowTime);
                padPullCloudInfoPO.setUpdateTime(nowTime);
                padPullCloudInfoPO.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                padPullCloudInfoPO.setInstructionType(0);
                padPullCloudInfoPOList.add(padPullCloudInfoPO);
                iPadFaceSyncDataServiceDao.updatePadOrderByUser(list.get(0).getUserId(),key);//清除当前设备,当前用户之前的1号指令
            }
        });
        if (!padPullCloudInfoPOList.isEmpty()){
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        }
    }

    /**
     * <desc>
     *      京东 人脸注册及用户权限变更推送平板指令
     * </desc>
     *
     * @param padFaceSyncDataDTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/12/9
     */
    private void faceRegister(PadFaceSyncDataDTO padFaceSyncDataDTO, List<PadPullCloudInfoPO> padPullCloudInfoPOList, Date nowTime) throws Exception{
        String facePicUrl = iPadFaceSyncDataServiceDao.getFacePicUrl(padFaceSyncDataDTO.getAppUserIds(),padFaceSyncDataDTO.getProjectId());
        String username = iPadFaceSyncDataServiceDao.getUsername(padFaceSyncDataDTO.getAppUserIds());
        List<String> deviceUniques = new ArrayList<>();
        //乘梯权限变更时
        if (StringUtils.isNotBlank(padFaceSyncDataDTO.getDeviceUniques())){
            deviceUniques = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getDeviceUniques());
        }else {
            deviceUniques = this.getPadDeviceUniqueList(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId());
        }
        List<AppFloorDevicesVO> floorDevices = iAppDeviceService.getFloorDevices(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId(), 1);

        //处理电梯
        List<Map<String,Object>> authsElevator = new ArrayList<>();
        if (floorDevices != null && !floorDevices.isEmpty()) {
            Map<String, Object> authElevator = new HashMap<>();
            List<Map<String,Object>> sysAuthElevator = new ArrayList<>();
            authElevator.put("userId",padFaceSyncDataDTO.getAppUserIds());
            authElevator.put("houseUserType","5");
            authElevator.put("startTime","");
            authElevator.put("endTime","");
            authElevator.put("deviceType",2);
            for (AppFloorDevicesVO floor : floorDevices) {
                Map<String,Object> sysAuth = new HashMap<>();
                sysAuth.put("auth",floor.getLiveFloor());
                sysAuth.put("deviceUnique",floor.getDeviceUnique());
                sysAuthElevator.add(sysAuth);
            }
            authElevator.put("sysAuths",sysAuthElevator);
            authsElevator.add(authElevator);
        }
        // 用户信息
        PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
        padFaceSyncDataUserVO.setUserName(username == null ? "" : username);
        padFaceSyncDataUserVO.setUserId(padFaceSyncDataDTO.getAppUserIds());
        padFaceSyncDataUserVO.setImageUrl(facePicUrl);
        // 先判断用户项目冻结状态
        String status = "1".equals(iPadFaceSyncDataServiceDao.getUserProjectStatus(padFaceSyncDataDTO.getAppUserIds(), padFaceSyncDataDTO.getProjectId())) ? "1" : "4";
        // 用户未冻结，则判断用户禁用状态
        if ("1".equals(status)) {
            status = "1".equals(iPadFaceSyncDataServiceDao.getUserStatus(padFaceSyncDataDTO.getAppUserIds())) ? "1" : "5";
        }
        padFaceSyncDataUserVO.setStatus(status);
        // 用户是否欠物业费用 0是 1否
        padFaceSyncDataUserVO.setOutstandingAccounts("1");
        padFaceSyncDataUserVO.setHouseUserType("5");
        padFaceSyncDataUserVO.setStartTime("");
        padFaceSyncDataUserVO.setEndTime("");
        List<PadFaceSyncDataUserVO> list = new ArrayList<>();
        list.add(padFaceSyncDataUserVO);

        for (String deviceUnique : deviceUniques){
            Integer accountByRoomId = null;
            PadPullCloudInfoPO padPullCloudInfoPO1 = new PadPullCloudInfoPO();
            padPullCloudInfoPO1.setDeviceUnique(deviceUnique);
            padPullCloudInfoPO1.setProjectId(padFaceSyncDataDTO.getProjectId());
            String syncData1 = JSON.toJSONString(list);
            padPullCloudInfoPO1.setSyncData(syncData1);
            padPullCloudInfoPO1.setSyncType(2);
            padPullCloudInfoPO1.setSyncSerialNo(LogicIdUtil.bussinessId());
            padPullCloudInfoPO1.setDataType(1);
            padPullCloudInfoPO1.setSyncStatus(1);
            padPullCloudInfoPO1.setStatus(DataStatusEnum.NORMAL.getType());
            padPullCloudInfoPO1.setCreateTime(nowTime);
            padPullCloudInfoPO1.setUpdateTime(nowTime);
            iPadFaceSyncDataServiceDao.updatePadOrderByUser(list.get(0).getUserId(),deviceUnique);//清除当前设备,当前用户之前的1号指令
            padPullCloudInfoPOList.add(padPullCloudInfoPO1);

            if (!authsElevator.isEmpty()) {
                PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
                padPullCloudInfoPO3.setDeviceUnique(deviceUnique);
                padPullCloudInfoPO3.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData3 = JSON.toJSONString(authsElevator);
                padPullCloudInfoPO3.setSyncData(syncData3);
                padPullCloudInfoPO3.setSyncType(2);
                padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO3.setDataType(2);
                padPullCloudInfoPO3.setSyncStatus(1);
                padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO3.setCreateTime(nowTime);
                padPullCloudInfoPO3.setUpdateTime(nowTime);
                padPullCloudInfoPO3.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                padPullCloudInfoPO3.setInstructionType(3);
                padPullCloudInfoPOList.add(padPullCloudInfoPO3);
            }
        }
        if (!padPullCloudInfoPOList.isEmpty()){
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        }
    }

    /**
     * <desc>
     *      访客人脸注册发送平板指令
     * </desc>
     *
     * @param padFaceSyncDataDTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/12/9
     */
    private void visitorFaceRegister(PadFaceSyncDataDTO padFaceSyncDataDTO, List<PadPullCloudInfoPO> padPullCloudInfoPOList, Date nowTime) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        Map<String,List<PadFaceSyncDataUserVO>> syncDataMapList = new HashMap<>();
        List<Map<String,Object>> authsElevator = new ArrayList<>();
        List<String> passIdList = StringHandlerUtil.splitStringList(padFaceSyncDataDTO.getPassId());
        List<AppVisitorPassCodeRecordPO> appVisitorPassCodeRecordPOS = iPadFaceSyncDataServiceDao.getJDVisitorByPassId(passIdList,padFaceSyncDataDTO.getProjectId());
        if (appVisitorPassCodeRecordPOS == null || appVisitorPassCodeRecordPOS.isEmpty()) {
            return;
        }
        AppVisitorPassCodeRecordPO appVisitorPassCodeRecordPO = appVisitorPassCodeRecordPOS.get(0);
        if (StringUtils.isBlank(appVisitorPassCodeRecordPO.getVFaceId())){
            return;
        }
        if ("1".equals(padFaceSyncDataDTO.getStatus())){
            //目前京东仅有电梯设备，暂不考虑门禁
            //获取邀请人的电梯权限
            List<AppFloorDevicesVO> floorDevices = iAppDeviceService.getFloorDevices(appVisitorPassCodeRecordPO.getUserId(), padFaceSyncDataDTO.getProjectId(), 1);
            if (floorDevices != null && !floorDevices.isEmpty()){
                Map<String, Object> authElevator = new HashMap<>();
                List<Map<String, Object>> sysAuthElevator = new ArrayList<>();
                authElevator.put("userId", appVisitorPassCodeRecordPO.getVFaceId());
                authElevator.put("houseUserType", "4");
                authElevator.put("startTime", sdf.format(appVisitorPassCodeRecordPO.getStartTime()));
                authElevator.put("endTime", sdf.format(appVisitorPassCodeRecordPO.getEndTime()));
                authElevator.put("deviceType", 2);
                for (AppFloorDevicesVO floor : floorDevices) {
                    Map<String,Object> sysAuth = new HashMap<>();
                    sysAuth.put("auth",floor.getLiveFloor());
                    sysAuth.put("deviceUnique",floor.getDeviceUnique());
                    sysAuthElevator.add(sysAuth);
                }
                authElevator.put("sysAuths", sysAuthElevator);
                authsElevator.add(authElevator);
            }
        }

        PadFaceSyncDataUserVO padFaceSyncDataUserVO = new PadFaceSyncDataUserVO();
        padFaceSyncDataUserVO.setUserName(appVisitorPassCodeRecordPO.getVisitorName() == null ? "" : appVisitorPassCodeRecordPO.getVisitorName());
        padFaceSyncDataUserVO.setUserId(appVisitorPassCodeRecordPO.getVFaceId());
        padFaceSyncDataUserVO.setImageUrl(appVisitorPassCodeRecordPO.getFacePicUrl());
        padFaceSyncDataUserVO.setStatus(padFaceSyncDataDTO.getStatus());
        // 用户是否欠物业费用 0是 1否
        padFaceSyncDataUserVO.setOutstandingAccounts("1");
        padFaceSyncDataUserVO.setHouseUserType("4"); // 4访客 5app住户
        padFaceSyncDataUserVO.setStartTime(sdf.format(appVisitorPassCodeRecordPO.getStartTime()));
        padFaceSyncDataUserVO.setEndTime(sdf.format(appVisitorPassCodeRecordPO.getEndTime()));
        List<String> deviceUniques = this.getPadDeviceUniqueList(appVisitorPassCodeRecordPO.getUserId(), padFaceSyncDataDTO.getProjectId());
        for (String deviceUnique : deviceUniques){
            if (syncDataMapList.get(deviceUnique) == null) {
                List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                list.add(padFaceSyncDataUserVO);
                syncDataMapList.put(deviceUnique,list);
            } else {
                syncDataMapList.get(deviceUnique).add(padFaceSyncDataUserVO);
            }
        }
        if (syncDataMapList.isEmpty()) {
            return;
        }

        syncDataMapList.forEach((key, value) -> {
            for (PadFaceSyncDataUserVO vo : value) {
                List<PadFaceSyncDataUserVO> list = new ArrayList<>();
                list.add(vo);
                PadPullCloudInfoPO padPullCloudInfoPO = new PadPullCloudInfoPO();
                padPullCloudInfoPO.setDeviceUnique(key);
                padPullCloudInfoPO.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData = JSON.toJSONString(list);
                padPullCloudInfoPO.setSyncData(syncData);
                padPullCloudInfoPO.setSyncType(2);
                padPullCloudInfoPO.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO.setDataType(1);
                padPullCloudInfoPO.setSyncStatus(1);
                padPullCloudInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO.setCreateTime(nowTime);
                padPullCloudInfoPO.setUpdateTime(nowTime);
                padPullCloudInfoPO.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                padPullCloudInfoPO.setInstructionType(4);
                iPadFaceSyncDataServiceDao.updatePadOrderByUser(list.get(0).getUserId(),key);//清除当前设备,当前用户之前的1号指令
                padPullCloudInfoPOList.add(padPullCloudInfoPO);
            }

            if (!authsElevator.isEmpty()) {
                List<PropertyDeviceCloudControllerEleVO> cloudElevatorList = new ArrayList<>();
                List<String> padDeviceUniqueList = new ArrayList<>();
                padDeviceUniqueList.add(key);
                List<Map<String, Object>> deviceUniqueMapList = iPropertyPadDao.getBindDeviceUniqueByPad(padDeviceUniqueList);//绑定设备编号逗号分隔
                if (deviceUniqueMapList.size() > 0 && deviceUniqueMapList.get(0).get("bindDeviceUnique") != null
                        && StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceUniqueMapList.get(0).get("bindDeviceUnique").toString()) == 5) {//只有一条此刻,判断是否绑定了群控器
                    String[] bindDeviceUniqueS = deviceUniqueMapList.get(0).get("bindDeviceUnique").toString().split(",");//绑定设备
                    for (String bindDeviceUnique : bindDeviceUniqueS) {
                        //根据群控器查询出对应云电梯
                        PropertyDeviceCloudControllerGetDTO propertyDeviceCloudControllerGetDTO = new PropertyDeviceCloudControllerGetDTO();
                        propertyDeviceCloudControllerGetDTO.setProjectId(padFaceSyncDataDTO.getProjectId());
                        propertyDeviceCloudControllerGetDTO.setDeviceId(bindDeviceUnique.substring(bindDeviceUnique.length() - 4, bindDeviceUnique.length()));
                        PropertyDeviceCloudControllerGetVO vo = null;
                        try {
                            vo = iDeviceCloudControllerService.getOne(propertyDeviceCloudControllerGetDTO);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        for (PropertyDeviceCloudControllerEleVO controller : vo.getCloudElevatorList()) {//将群控器编号放回list中
                            controller.setDeviceUniqueContrroller(vo.getDeviceUnique());
                        }
                        //拼接所有云电梯
                        cloudElevatorList.addAll(vo.getCloudElevatorList());
                    }
                    //判断云电梯是否为绑定群控器控制,并替换云电梯的设备编号为群控器编号
                    for (Map<String, Object> mapUser : authsElevator) {
                        List<Map<String, Object>> sysAuths = (List<Map<String, Object>>) mapUser.get("sysAuths");
                        //存电梯对象的新容器
                        Map<String, Object> sMap = new HashMap<>();
                        //替换原sysAuths的新容器
                        List<Map<String, Object>> newSysAuths = new ArrayList<>();
                        //判断已遍历过的电梯对应群控机号是否已处理过
                        Set<String> deviceUniqueSet = new HashSet<>();
                        for (Map<String, Object> mapAuth : sysAuths) {//循环权限
                            //找出当前sysAuth对应的控制器信息
                            Optional<PropertyDeviceCloudControllerEleVO> optional = cloudElevatorList.stream().filter(vo -> vo.getDeviceUniqueElevator().equals(mapAuth.get("deviceUnique").toString())).findFirst();
                            PropertyDeviceCloudControllerEleVO controllerVo = optional.isPresent() ? optional.get() : null;
                            if (controllerVo != null) {//有当前群控器管控的云电梯时
                                if (deviceUniqueSet.add(controllerVo.getDeviceUniqueContrroller())) {
                                    //第一次处理
                                    mapAuth.put("deviceUnique", controllerVo.getDeviceUniqueContrroller());
                                    sMap.put(controllerVo.getDeviceUniqueContrroller(), mapAuth);
                                } else {
                                    Map<String, Object> repeatMap = (HashMap) sMap.get(controllerVo.getDeviceUniqueContrroller());
                                    //替换操作 mapAuth  / repeatMap
                                    String auth = StringHandlerUtil.duplicateEemoval(mapAuth.get("auth").toString() + "," + repeatMap.get("auth"));
                                    repeatMap.put("auth", auth);
                                }
                            } else {//没有管控的直接无条件添加
                                newSysAuths.add(mapAuth);
                                continue;
                            }
                        }
                        for (String keys : sMap.keySet()) {
                            newSysAuths.add((HashMap) sMap.get(keys));
                        }
                        mapUser.put("sysAuths", newSysAuths);
                    }
                }
                //推送权限信息
                PadPullCloudInfoPO padPullCloudInfoPO3 = new PadPullCloudInfoPO();
                padPullCloudInfoPO3.setDeviceUnique(key);
                padPullCloudInfoPO3.setProjectId(padFaceSyncDataDTO.getProjectId());
                String syncData3 = JSON.toJSONString(authsElevator);
                padPullCloudInfoPO3.setSyncData(syncData3);
                padPullCloudInfoPO3.setSyncType(2);
                padPullCloudInfoPO3.setSyncSerialNo(LogicIdUtil.bussinessId());
                padPullCloudInfoPO3.setDataType(2);
                padPullCloudInfoPO3.setSyncStatus(1);
                padPullCloudInfoPO3.setStatus(DataStatusEnum.NORMAL.getType());
                padPullCloudInfoPO3.setCreateTime(nowTime);
                padPullCloudInfoPO3.setUpdateTime(nowTime);
                padPullCloudInfoPO3.setSourceSystem(padFaceSyncDataDTO.getSourceSystem());
                padPullCloudInfoPO3.setInstructionType(4);
                padPullCloudInfoPOList.add(padPullCloudInfoPO3);
            }
        });
        if (!padPullCloudInfoPOList.isEmpty()){
            iPadFaceSyncDataServiceDao.batchSave(padPullCloudInfoPOList);
        }
    }

    /**
     * <desc>
     *      根据用户电梯权限找出绑定的平板
     * </desc>
     *
     * @param userId 用户id
     * @param projectId 项目id
     * @return
     * @Author Zhu.yj
     * @createDate  2020/12/8
     */
    private List<String> getPadDeviceUniqueList(String userId, String projectId){
        List<String> elevatorDeviceUniqueList = new ArrayList<>();
        List<String> deviceUniques = new ArrayList<>();
        List<AppElevatorAuthDTO> auth = iAppDeviceDao.getFloorAuth(userId, projectId);
        AppElevatorAuthVO elevator = StringHandlerUtil.convertElevatorAuth(auth);
        //解析电梯权限
        List<String> deviceIdList = StringHandlerUtil.splitStringList(elevator.getDeviceId());
        if (!deviceIdList.isEmpty()){
            for (String deviceId : deviceIdList){
                elevatorDeviceUniqueList.add(StringHandlerUtil.getDeviceUniqueId(projectId,1, deviceId));
            }
            //根据电梯deviceUnique找出绑定该电梯的平板deviceUnique列表
            deviceUniques = iPadFaceSyncDataServiceDao.getBindElevatorPadList(elevatorDeviceUniqueList);
        }
        return deviceUniques;
    }

    /**
     * <desc>
     * 上传图片文件
     * <desc/>
     *
     * @param bytes     图片二进制
     * @param imageType 图片类型
     * @return
     * @author Qiang.S
     * @createDate 2018-05-18
     */
    protected String uploadImageFile(byte[] bytes, String imageType, FileCatalogEnum fileCatalog) {
        byte[] newbytes = ImgageUtil.stringToImage(bytes, imageType);
        ByteArrayInputStream byteArrayInputStream = null;
        if (newbytes != null) {
            byteArrayInputStream = new ByteArrayInputStream(newbytes);
        } else {
            byteArrayInputStream = new ByteArrayInputStream(bytes);
        }
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );

        try {
            //log.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //log.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)) {
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            } else {
                LOG.info(String.format("图片上传失败，returnCode: %s", returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }

}
